spring注入之使用标签 @Autowired @Qualifier

  使用标签的缺点在于必需要有源代码(由于标签必须放在源代码上),当我们并没有程序源代码的时候。我们仅仅有使用xml进行配置。

比如我们在xml中配置某个类的属性

          

  1. <bean name="studentService"class="com.bjsxt.service.StudentService">  
  2.     <property name="studentDao"ref="stuDaoImpl"></property><!-- 普通值用value 对于特定的类的对象则用ref须要注意的是 ref须要在xml文件里进行配置-->  
  3.   </bean>  

(1)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"> <context:annotation-config /><!-- 自己主动装配一定要加上此片段--> <bean name="s"class="com.bjsxt.dao.impl.StudentDaoImpl"></bean> <bean name="student"class="com.bjsxt.model.Student" scope="singleton" lazy-init="true"init-method="init" destroy-method="destroy"></bean> <!-- prototype 每次生成的对象不同 prototype lazy-init=false 默认在容器进行初始化的时候就初始化了该对象 --> <bean name="studentService"class="com.bjsxt.service.StudentService"> </bean> </beans>



(2)类 注意在这里的两种装配方式 第一种由于破坏了封装性不建议 spring容器在进行查找时。是依照xml进行查找

packagecom.bjsxt.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
 
importcom.bjsxt.dao.*;
import com.bjsxt.dao.impl.*;
importcom.bjsxt.model.*;
public class StudentService {
    /*@Autowired //依照类型进行匹配
     @Qualifier("s")依照名称进行匹配    第一种表示方式放在属性名的前面
    */
privateStudentDao studentDao;
//减少了耦合性:StudentService并不知道详细由谁来保存学生s 由ioc容器来控制装配
 
publicStudentDao getStudentDao() {
    return studentDao;
}
@Autowired//放到set方法上
public void setStudentDao( @Qualifier("s")StudentDao studentDao) {
    this.studentDao = studentDao;
}
public void add(Student s)
{
    this.studentDao.StudentSave(s);
}
}
 


posted @ 2017-04-26 12:07  zhchoutai  阅读(437)  评论(0编辑  收藏  举报