Spring Bootダイナミック注入の2つの方法


@Profile+spring.profiles.activeを通じて
spring.profiles.active:公式解釈では、異なる環境でのプロファイルをアクティブにしていますが、実際のテストでは対応するプロファイルがないことが分かりました.正常に実行できます.このkeyをパラメータとして使ってもいいです.@Profile:spring.profiles.activeでアクティブにしている配置はspringでこのbeanを管理しています.@Component、@Service、@Controller、@Repositoryなどに合わせて使います.
@Component
@Profile("xx")
public class XxxTest extends BaseTest {
    public void test(){
        System.out.println("in XxxTest ");
    }
}
@Component
@Profile("yy")
public class YyyTest extends BaseTest {
    public void test(){
        System.out.println("in YyyTest ");
    }
}
 
@Service
public class MyService  {
 
 @Autowired
 private BaseTest  test;
 
    public void printConsole(){
        test.test();
    }
}
 
//           test      bean
spring.profiles.active=xx
@Configrationn@Comptional OnProptyを通じて
@Configration:既存のspring.xmlに相当し、spring@Contintional OnPropertyを配置するために使用されています.アクティブなプロファイルのいずれかの値から、あるbeanを信託管理するかどうかを判断します.org.springframe ork.boot.atoconfireg.com.com.comパッケージには多くの注釈が含まれています.状況に応じて選択できます.
@Configuration
public static class ContextConfig {
@Autowired
private XxxTest xxTest;
@Autowired
private YyyTest yyTest;
 
@Bean
@ConditionalOnProperty(value = "myTest",havingValue = "xx")
 public BaseTest  xxxTest() {
  return xxTest;
 }
 
 @Bean
@ConditionalOnProperty(value = "myTest",havingValue = "yy")
 public BaseTest yyyTest() {
  return yyTest;
 }
//           bean
myTest=xx
}