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);
}
}
 


转载于:https://www.cnblogs.com/zhchoutai/p/6767905.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值