通過@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 {@Autowiredprivate 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
}