Spring Boot 动态注入的两种方式

1,884 阅读2分钟
原文链接: yq.aliyun.com

Spring Boot 动态注入的两种方式

meijm0103 2019-03-26 14:03:11 浏览184 评论0

摘要: 通过@Profile+spring.profiles.active spring.profiles.active:官方解释是激活不同环境下的配置文件,但是实际测试发现没有对应的配置文件也是可以正常执行的。

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

参考资料

blog.csdn.net/wild46cat/a…
www.javacodegeeks.com/2013/10/spr…

【云栖快讯】一站式开发者服务,海量学习资源免费学  详情请点击 评论 (0) 点赞 (0) 收藏 (1)
分享到:

相关文章

网友评论