[Spring]6.注解实现自动装配

使用注解的条件

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/>

</beans>

即添加了context的依赖:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
并通过<context:annotation-config/ >开启注解

注解实现自动装配

可以在变量名或者setter方法上添加@Autowired或者@Resource

@Autowired

默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如 @Autowired(required=false)。
默认使用ByType。如果上下文中有多种相同类型的bean,则会通过ByName。
通常需要搭配@Qualifier(value = "xxx")来指定bean的名称。

@Resource

默认按照名称进行装配,名称可以通过name属性进行指定,如 @Resource(name = "xxx")
当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

image

posted @ 2021-11-23 21:44  从零开始学java_wxz  阅读(34)  评论(0)    收藏  举报