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"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[小G]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值