Spring限定性依赖注入-@Primary @Qualifier

本文介绍了在Spring中如何解决多个Bean选择注入的歧义问题,重点讲解了@Primary注解如何标记首选Bean,以及@Qualifier注解如何进行更细粒度的过滤。同时,还探讨了自定义限定注解的使用和泛型在限定注入中的作用。
摘要由CSDN通过智能技术生成

Spring自动匹配Bean注入的机制在有多个可选的Bean存在时是不可用的,需要进一步进行相关配置明确消除多个可选Bean存在的歧义性。基于Java注解的注入可通过@Primary@Qualify完成。

@Primary注解

符合@Autowired连接的候选bean有多个,如果依赖注入只需要一个bean, 在只有其中一个bean声明了@Primary的情况下,该bean将会被注入。

@Configuration
public class MovieConfiguration {
   

    @Bean
    @Primary
    public MovieCatalog firstMovieCatalog() {
    ... }

    @Bean
    public MovieCatalog secondMovieCatalog() {
    ... }

    // ...

}

public class MovieRecommender {
   

    @Autowired
    private MovieCatalog movieCatalog; 

    // ...

}

firstMovieCatalog被注入。
xml形式的配置中,<bean>元素的primary=true属性提供了同样的功能。

@Qualifier注解

@Primary只能取其一作为首要依赖被注入,而@Qualifier提供了更细粒度的过滤,可以取其一,也可以取多个。
@Qualifier通过其标示值参数过滤掉不符合条件的bean,缩小符合依赖注入条件的范围。

@Qualifier用于注解注入域

public class MovieRecommender {
   

    @Autowired
    @Qualifier("main")
    private MovieCatalog movieCatalog;

    // ...

}

@Qualifier也可注解单独的方法参数(包括构造器参数)

public class MovieRecommender {
   

    private MovieCatalog movieCatalog;

    private CustomerPreferenceDao customerPreferenceDao;

    @Autowired
    public void prepare(@Qualifier("main")MovieCatalog movieCatalog,
            CustomerPreferenceDao customerPreferenceDao) {
   
        this.movieCatalog = movieCatalog;
        this.customerPreferenceDao = customerPreferenceDao;
    }

    // ...

}

定义了以下两个Bean的情况下

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <bean class="example.SimpleMovieCatalog">
        <qualifier value="main"/>

        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值