Spirng——注解实现Bean自动装配
Spirng——注解实现Bean自动装配
使用须知:
1.导入约束:context约束
2.配置注解的支持: context:annotation-config/
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
@Autowired
通过ByType的方式实现自动装配,且必须要求该对象存在。
直接在属性上使用,也可以在set方法上使用。
使用Autowired时,可以不用编写set方法,前提是你这个自动装配的属性在IOC容器中存在,且符合Byname方式
@Autowired
private Cat cat;
1
2
@Qualifier
@Autowired
@Qualifier(value = "dog111")
private Dog dog;
1
2
3
如果@Autowired自动装配的环境比较复杂,可以使用@Qualifier来辅助@Autowired完成自动装配,
通过@Qualifier(value = “dog111”)指定Bean的ID来装配。
————————————————
版权声明:本文为CSDN博主「XIaoyummm」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/XIaoyummm/article/details/114735415