通过 @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://yq.aliyun.com/articles/695299