【问题标题】:Autowire a specific bean given a profile自动装配给定配置文件的特定 bean
【发布时间】:2019-01-29 09:43:18
【问题描述】:

我有 2 个实现 InterfaceA 的类

@Service("classA")
class ClassA implements InterfaceA

@Service("classB")
class ClassB implements InterfaceA

我需要加载两个 bean。但是,在 C 类和 D 类中,我需要指定我需要的 bean

class ClassC {
    @Autowired
    @Qualifier("classA")
    private InterfaceA interf;
}

class ClassD {
    @Autowired
    @Qualifier("classA")
    private InterfaceA interf;
}

但是,我有 2 个配置文件,profile1 和 profile2。如果我使用 -Dspring.profiles.active=profile1,我应该对 classC 和 classD 使用限定符“classA”。如果我使用 -Dspring.profiles.active=profile2,我应该使用“classB”作为限定符。此外,无论配置文件如何,另一个 ClassE 都应始终使用 classB。你能告诉我应该怎么做吗?

【问题讨论】:

  • 您能进一步解释一下您的用例吗?如果更具体一点,可能有助于确定一个合理的解决方案。
  • 我有 2 个部署。一个在本地服务器中,另一个在云中。我需要在云中使用 classB,因为它与 classA 有不同的实现,仅适用于本地服务器。
  • 那你为什么需要创建两个 bean?
  • 因为 ClassD 中有两个配置文件都使用的实现,所以我需要让两个 bean 都可用。
  • 听起来你让事情变得不必要地复杂,但做你想做的事情的方法可能是有一个带有嵌套子配置的@Configuration 类,每个子配置都有一个配置文件集它并专门配置它的bean。

标签: java spring


【解决方案1】:

所以我就是这样做的。我创建了一个配置类

@Configuration
public class ConfigClass {
    @Autowired
    private ClassB classB;

    @Profile("profile1")
    @Qualifier("myclass")
    @Bean
    private InterfaceA classAtProfile1() {return new ClassA();}

    @Profile("profile2")
    @Qualifier("myclass")
    @Bean
    private InterfaceA classAtProfile2() {return classB;}
}

class ClassA implements InterfaceA

@Service("classB")
class ClassB implements InterfaceA

这样,我可以根据配置文件自动装配 InterfaceA

@Autowired
@Qualifier("myclass")
private InterfaceA myclass;

虽然 ClassE 仍然可以引用 classB

@Component
public class ClassE {
    @Autowired
    ClassB classB;
    ...
}

【讨论】:

    【解决方案2】:

    定义2个配置java文件:

    class ClassA implements InterfaceA
    
    class ClassB implements InterfaceA
    

    示例配置文件 1:

    Profile1Config.java

     @Configuration
     @Profile("profile1")
     public class Profile1Config {
        @Bean
        public InterfaceA interfaceA() {
           return new ClassA();
        }
     }
    

    示例配置文件 2:

    Profile1Config.java

     @Configuration
     @Profile("profile2")
     public class Profile2Config {
        @Bean
        public InterfaceA interfaceA() {
           return new ClassB();
        }
     }
    

    无论你想在哪里使用它:

    class ClassC {
       @Autowired
       private InterfaceA interf;
    }
    
    class ClassD {
        @Autowired
        private InterfaceA interf;
    }
    

    需要注意的关键点: 1. @Qualifier 不是必需的。 2. @Profile 在 Java Configuration 类中被提及。 3. @Service 已从 classA 和 classB 中删除,而是现在在 Config* 类中定义。

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 2015-08-06
      • 2018-06-15
      • 1970-01-01
      相关资源
      最近更新 更多