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

猜你喜欢

转载自yq.aliyun.com/articles/695299