zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    [Canvas学习]变形
    [Canvas学习]样式与颜色
    [Canvas学习]绘制图形
    上海 day31--线程
    上海 day31--进程间通信IPC机制、生产者与消费者模型
    关于 序列化模块 json 的小问题和小理解!!!
    上海 day30--并发编程、进程
    上海 day29-- UDP协议通信和socketserver模块
    上海 day28--套接字socket
    易用常用的小知识点
  • 原文地址:https://www.cnblogs.com/springmorning/p/10391189.html
Copyright © 2011-2022 走看看