【问题标题】:Spring @Autowire field based on @Profile基于@Profile 的Spring @Autowire 字段
【发布时间】:2016-07-13 09:06:30
【问题描述】:

我需要根据 spring.profiles.active 属性自动装配字段。 该服务仅基于配置文件创建,但由于该服务在其他类中自动装配,因此我无法使用 @Profile 注释。

有没有办法根据配置文件自动连接字段。

【问题讨论】:

    标签: spring spring-profiles


    【解决方案1】:

    您可以为每个配置文件创建不同的服务实现。

    在下面的示例中,我使用 mockito 来模拟 dataSource bean

    例如

     @Configuration
        @ComponentScan
        class YourConfig {
    
            @Profile("production")
            @Qualifier("datasource")
            @Bean
            public DataSource dataSourceProduction(){
               return new DataSourceProduction()
            }
    
            @Profile("development")
            @Qualifier("datasource")
            @Bean
            public DataSource dataSourceDevelopment(){
               return mock(DataSourceProduction.class);
            }
    

    【讨论】:

    • 想要避免创建模拟。但谢谢我想我也必须这样做。
    • 根据您要完成的任务,您不必创建这样的模拟......但最初的问题不够明确,不能称之为错误。
    • 问题是如何告诉 spring:只有在激活配置文件 X 时,才会在我的班级中自动装配此字段。
    猜你喜欢
    • 2021-12-31
    • 2020-06-21
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2018-09-14
    • 1970-01-01
    相关资源
    最近更新 更多