spring注入之使用标签 @Autowired @Qualifier
2024-09-04 14:20:42
使用标签的缺点在于必需要有源代码(由于标签必须放在源代码上),当我们并没有程序源代码的时候。我们仅仅有使用xml进行配置。
比如我们在xml中配置某个类的属性
- <bean name="studentService"class="com.bjsxt.service.StudentService">
- <property name="studentDao"ref="stuDaoImpl"></property><!-- 普通值用value 对于特定的类的对象则用ref须要注意的是 ref须要在xml文件里进行配置-->
- </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);
}
}
最新文章
- 使用EF Oracle实现DevExpress绑定大数据的ServerMode模式
- maven File encoding has not been set
- Android中Activity、Service和线程之间的通信
- apache+tomcat整合
- Eclipse 环境安装和配置优化
- C++中的重载,隐藏,覆盖,虚函数,多态浅析
- 背包问题递归java
- .NET 创建并写CSV文件
- C#Redis字符串
- Postman 测试web接口(推荐)
- Codeforces Round #424 (Div. 2, rated, based on VK Cup Finals)A B题
- 你为什么还坚持.NET
- PageRank_网页排名_MapReduceJava代码实现思路
- c# winform打印excel(使用NPOI+Spire.xls+PrintDocument直接打印excel)
- 【c#】队列(Queue)和MSMQ(消息队列)的基础使用
- Oracle高级查询之over(partition by...)
- JavaSE-类
- Spring Boot + Spring Cloud 实现权限管理系统 后端篇(八):MyBatis分页功能实现
- CSS样式----css样式表和选择器(图文详解)
- Load balancing 各组件的比较