读书人

spring依赖注入之诠注方式驱动依赖注入

发布时间: 2012-11-08 08:48:12 作者: rapoo

spring依赖注入之注解方式驱动依赖注入
<?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"> <context:annotation-config/> </beans>

??

3、修改以上配置文件的头信息后,我们就可以在Java代码通过注解方式来注入bean,看下面代码

(1)@Resource

public class StudentService3 implements IStudentService {  //@Resource(name="studentDao")放在此处也是可行的    private IStudentDao studentDao;    private String id;         public void setId(String id) {  this.id = id; } @Resource(name="studentDao") //通过此注解完成从spring配置文件中查找名称为studentDao的bean来装配字段studentDao,如果spring配置文件中不存在studentDao名称的bean则转向按照bean类型经行查找 public void setStudentDao(IStudentDao studentDao) {  this.studentDao = studentDao; }     public void saveStudent() {  studentDao.saveStudent();  System.out.print(",ID为:"+id); }}

??

配置文件添加如下信息

? <bean id="studentDao" />

?

(2)@Autowired

?

public class StudentService3 implements IStudentService {  //@Autowired放在此处也是可行的    private IStudentDao studentDao;    private String id;        public void setId(String id) {  this.id = id; } @Autowired//通过此注解完成从spring配置文件中查找满足studentDao类型的bean  //@Qualifier("studentDao")则按照名称经行来查找转配的 public void setStudentDao(IStudentDao studentDao) {  this.studentDao = studentDao; }     public void saveStudent() {  studentDao.saveStudent();  System.out.print(",ID为:"+id); }}

??

配置文件添加如下信息

? <bean id="studentDao" />

?

4.spring2.5还提供了对受管组件的Classpath扫描,它可以使spring配置文件减少使用<bean></bean>来配置元数据bean

读书人网 >软件架构设计

热点推荐