9-注解实现自动装配

 

使用注解实现自动装配

点击跳转到工程

spring除了用xml配置文件来实现属性注入以外,还可以使用注解实现注入

@Autowired   //通过byType实现自动装配,而且必须要求这个对象存在
@Resource		//默认通过byName实现自动装配,如果找不到名字,就通过byType自动装配,2个都不行的话就报错

使用@Autowired注入

要使用注解,首先要在xml文件中提供注解支持

image-20210801104937636

beans.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="dog" class="com.ajream.pojo.Dog"/>
    <bean id="cat" class="com.ajream.pojo.Cat"/>
    <bean id="person" class="com.ajream.pojo.Person" />


</beans>

注意:使用byType自动装配时,若有多个相同类型的bean,把primary属性值设为true说明首先使用该bean

Person类中:(可以没有setter方法)

public class Person {
    @Autowired
    private Cat cat;
//...
}

@Autowired就相当于:

<bean class="com.ajream.pojo.Person"  autowire="byType"/>

还可以将 @Autowired 注释应用于传统的 setter 方法,如以下示例所示:

public class SimpleMovieLister {

    private Cat cat;

    @Autowired
    public void setCat(Cat cat) {
        this.cat = cat;
    }

    // ...
}

由于按类型自动装配可能会导致多个候选对象,因此通常需要对选择过程进行更多控制。因此可以使在bean中配置 primary属性 (下面是官方例子)

    <bean class="example.SimpleMovieCatalog" primary="true" />

    <bean class="example.SimpleMovieCatalog"/>

    <bean id="movieRecommender" class="example.MovieRecommender"/>

primary 表示当多个 bean 是自动装配到单值依赖项的候选者时,应优先考虑特定 bean。如果候选中恰好存在一个主要 bean,则它成为自动装配的值。

@Qualifier

当有多个bean类型相同,但id不同时,可以使用@Qualifier 来指定使用哪一个bean

public class Person {
    @Autowired
    @Qualifier(value = "cat22")
    private Cat cat;
//...
}
<bean id="cat22" class="com.ajream.pojo.Cat"/>
<bean id="cat23" class="com.ajream.pojo.Cat"/>

<bean class="com.ajream.pojo.Person"  autowire="byType"/>

@Nullable

字段使用了这个注解,说明该字段可以为 null

使用@Resource 注入

@Resource 采用 name 属性。默认情况下,Spring 将该值解释为要注入的 bean 名称。

public class Person {
    @Resource(name="cat22")
    private Cat cat;
//...
}
<bean id="cat22" class="com.ajream.pojo.Cat"/>
<bean id="cat23" class="com.ajream.pojo.Cat"/>

<bean class="com.ajream.pojo.Person"  autowire="byType"/>
posted @   aJream  阅读(43)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示