之前讲了xml中的autowire,是在被注入的bean上写autowire=“byName”当然还可以byType,default等等。
当然autowire这句话可以放到annotation中,这样的好处是
1、xml中的bean特别的整洁,每一行写一个bean,没有bean之间相互注入的关系,没有autowire的补丁。
2、由于整洁,可以只让程序员只关注bean,而把关系放到annotation中,这样更有条理。bean负责生成类的实例,注入由annotation负责
需要用到上一个例子
使用xml的autowire
现在修改springbean.xml为下面这个样子
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 新增xml的命名空间,接下来会用到context标签 -->
<!-- context对应的链接 -->
<!-- context对应的xsd -->
<context:annotation-config></context:annotation-config><!-- 表示使用annotation进行配置 -->
<bean id = "dao" class="com.spring.dao.UserDao"></bean>
<bean id="userService" class ="com.spring.service.UserService">
</bean>
</beans>
新增命名空间的配置。
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
新增了<context:annotation-config></context:annotation-config>标签,表示使用注释的方式进行配置。
同时删除掉xml文件中userService bean的autowire的配置。
在UserService类setDao方法上面增加@Autowired
package com.spring.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.spring.dao.UserDao;
public class UserService {
private UserDao dao;
public UserDao getDao() {
return dao;
}
@Autowired
public void setDao(UserDao dao) {
this.dao = dao;
}
public void add()
{
dao.add();
}
}
测试一下,还是不行,因为使用annotation需要导入一个jar包
现在导入common-annotations.jar
导入后入下图。
再测试一下,就ok了
从现在起都提供源代码以供参考。请自行下载源码吧
- 大小: 13.3 KB
分享到:
相关推荐
Spring Annotation
spring使用annotation整合dwr笔记 spring使用annotation整合dwr笔记 spring使用annotation整合dwr笔记
Spring_Annotation_AOP
spring的Annotation注解.
spring 使用annotation替代xml配置实例
Spring annotation 样例
Spring的Annotation配置相关讲义
马士兵视频里的struts2 hibernate3 spring2.5 annotation 整合 绝对好用 里面还有jar包 部署就可以用
Spring+mybatis annotation形式 进行增删查改,使用maven容器,配置完整,自己运行多次无问题
Spring IOC Annotation 注入 学习实例
Dwr3+Spring3 全注解 annotation 方式实现
详解 Spring 3.0 基于 Annotation 的依赖注入实现。。详解 Spring 3.0 基于 Annotation 的依赖注入实现。。
花了些时间做了一个实验,彻底弄懂了spring Annotation注入的方式。凡带有@Component,@Controller,@Service,@Repository 标志的等于告诉Spring这类将自动产生对象,而@Resource则等于XML配置中的ref,告诉spring此处...
spring3、 hibernate4 配置声明式事务管理(annotation方式)
NULL 博文链接:https://tianhei.iteye.com/blog/978969
配置整合DWR3.0和Spring2.5使用annotation注解
spring加入hibernate annotation方式第一部分,需要其他部分请查看本人其他资源
spring annotation注解 使用Spring注解来注入属性