注解方式中重点掌握@Autowired方式
1.使用前提
-
导入约束: xmlns:context=“http://www.springframework.org/schema/context”
-
配置注解的支持: 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>
2.使用
如何在先有的基础上,通过复制粘贴和修改实现 导入约束+配置注解的支持
清理出一个很干净的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
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/>
<!--将实体类注册到容器中-->
<bean id="cat1" class="com.thhh.pojo.Cat"/>
<bean id="dog2" class="com.thhh.pojo.Dog"/>
<bean id="person" class="com.thhh.pojo.Person"/><!--这里已近没有了自动装配属性的设置-->
</beans>
3.@Autowired
这个注解我们需要加在需要进行自动装配的属性/属性的set方法上
使用这个注解还有一个好处:我们可以不写需要自动装配的属性的set方法
- 使用的前提:这个属性在IOC容器中已经注册好了,且注册在容器中的bean满足byName的使用条件或byType的使用条件(必须有set方法存在),使用的时候它会先使用byType进行自动装配,byType失败就使用byName进行自动装配
- 使用@Autowired,如果想让自动注入的属性为null并且不报错,我们有两种处理方法
- 在参数前面添加注解@Nullable
- 在参数前面添加注解@Nullable
这就是@Nullable的作用,如果我们将有参构造前面的@Nullable去掉再来测试
报错的原因就是person注册的对象没有为有参构造指定参数,这就导致了容器不能调用它的有参构造来实例化这个对象,所以我们在获取容器的时候就报错了,因为获取容器的时候,容器会将所有注册的类都实例化
- 为使用@Autowired注解的地方传入参数"request = false"
效果:即使这个属性为NULL,也不会报错
4.@Qualifier
注解@Qualifier是配合@Autowired 一起/配套 使用的,它的使用场景就是当注解@Autowired的使用条件都不满足的时候,即容器中这个对象属性的时候既不满足byName自动装配的使用条件,又不满足byType自动装配的使用条件
此时,我们就可以通过@Qualifier注解,按照byName显式的为这个对象属性指定一个bean,这样容器就知道怎么自动装配person bean了
5.@Resource注解实现和@Autowired相同效果
首先,这个注解在javax.annotation.Resource包中,但是JDK11以后完全移除了javax扩展,所以不能直接使用@resource注解
解决办法:通过maven引入依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
@Resource的作用 = @Autowired+@Qualifier,但是开发中最常用的还是@Autowired注解
6.小结
- @Autowired:自动装配,先通过type,再使用name,都不行就报错
- @Qualifier:配合@Autowired使用,当@Autowired报错时,使用@Qualifier(value=“指定bean的ID值”)
- @Resource:Java自己的注解,使用的使用如果JDK>=11,可以使用maven依赖导入javax包,否则这个注解使用不了
- @Resource先通过name,再使用type自动装配,都不行就报错
- 可以通过@Resource(name = “XXX”)实现和@Qualifier相同的效果
- @Nullable和@Autowired(required = false)效果相同,可以使得对象属性为NULL也不报错