Spring Boot 動態注入的兩種方式

通過@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

通過@Configuration+@ConditionalOnProperty

@Configuration:相當於原有的spring.xml,用於配置spring
@ConditionalOnProperty:依據激活的配置文件中的某個值判斷是否託管某個bean,org.springframework.boot.autoconfigure.condition包中包含很多種註解,可以視情況選擇

@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
}

參考資料

https://blog.csdn.net/wild46cat/article/details/71189858
https://www.javacodegeeks.com/2013/10/spring-4-conditional.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章