Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.9.3 使用@Primary微调基于注解的自动装配

由于按类型自动装配可能会多个候选,因此通常需要对选择过程进行更多控制。实现这一目标的一种方法是使用Spring@Primary @Primary表明当多个bean可以自动装配到单值依赖项时,应该优先选择定的bean。如果候选者中只存在一个primary”bean,则它将是自动装配的值。

假设我们有以下配置将firstMovieCatalog定义为primary MovieCatalog

@Configuration
public class MovieConfiguration { @Bean @Primary public MovieCatalog firstMovieCatalog() { ... } @Bean public MovieCatalog secondMovieCatalog() { ... } // ... }

通过这样的配置,以下MovieRecommender将与firstMovieCatalog进行自动装配。

public class MovieRecommender {

    @Autowired
    private MovieCatalog movieCatalog;

    // ...

}

相应的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" primary="true">
        <!-- inject any dependencies required by this bean -->
    </bean>

    <bean class="example.SimpleMovieCatalog">
        <!-- inject any dependencies required by this bean -->
    </bean>

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

原文地址:https://www.cnblogs.com/springmorning/p/10391189.html