【问题标题】:Spring Boot - Using Qualifiers with ProfilesSpring Boot - 将限定符与配置文件一起使用
【发布时间】:2022-01-31 20:23:59
【问题描述】:

我有以下使用限定符和配置文件dev。当!dev Service1 将使用基于限定符的FooImpl1Service2 将使用FooImpl2。当配置文件为dev 时,我希望两个服务都使用FooImpl3。我怎样才能做到这一点?

interface Foo {
  public void fooToYou();
}

@Component("fooImpl1")
@Profile("!dev")
public class FooImpl1 implements Foo {
  @Override
  public void fooToYou() {}
}

@Component("fooImpl2")
@Profile("!dev")
public class FooImpl2 implements Foo {
  @Override
  public void fooToYou() {}
}

@Component("fooImpl3")
@Profile("dev")
public class FooImpl3 implements Foo {
  @Override
  public void fooToYou() {}
}

public class Service1 {
  @Autowired
  public void Service1(@Qualifier("fooImpl1") Foo foo) {}
}

public class Service2 {
  @Autowired
  public void Service1(@Qualifier("fooImpl2") Foo foo) {}
}

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我想出了一种方法来完成我最终试图通过删除限定符和使用继承来完成的事情。

    interface BaseFoo {
      public void fooToYou();
    }
    
    interface Foo1 extends BaseFoo {}
    interface Foo2 extends BaseFoo {}
    
    @Profile("!dev")
    class FooImpl1 implements Foo1 {
      @Override
      public void fooToYou() {}
    }
    
    @Profile("!dev")
    class FooImpl2 implements Foo2 {
      @Override
      public void fooToYou() {}
    }
    
    class BaseDevFooImpl implements BaseFoo {
      @Override
      public void fooToYou() {}
    }
    
    @Profile("dev")
    class DevFooImpl1 extends BaseDevFooImpl implements Foo1 {}
    
    @Profile("dev")
    class DevFooImpl2 extends BaseDevFooImpl implements Foo2 {}
    
    class Service1 {
      @Autowired
      public void Service1(Foo1 foo) {}
    }
    
    class Service2 {
      @Autowired
      public void Service1(Foo2 foo) {}
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2021-01-02
      • 2020-03-09
      • 2019-08-05
      • 2016-01-29
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2015-11-03
      相关资源
      最近更新 更多