Spring学习总结(八):注解实现自动装配

一、使用注解

1、导入约束:context约束
2、配置注解的支持:context:annotation-config/


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

二、@AutoWired

1、可以直接在属性上使用,也可以在 set 方法上使用‘
2、使用 @AutoWired 就可以省略 set 方法
3、如果 @AutoWired 自动配置的环境比较复杂,自动装配无法通过一个注解 @AutoWired 完成的时候,可以使用 @Qualifier (value=xxx)去配合 @AutoWired 的使用,指定一个唯一的 bean 对象注入,也可以通过 @Resource(name=xxx)

三、@AutoWired 和 @Resource

1、相同点:都是用来自动装配的,可以用在属性字段上
2、不同点
① @AutoWired :是先通过 byType 实现,再 byName 实现
② @Resource :默认通过 byName 的方式实现,找不到再通过 byType

你可能感兴趣的:(Spring)