一、@Profile的作用:
可以根據當前環境,動態的激活和切換一系列組件的功能,指定組件在哪個環境的情況下才能被註冊到容器中,不指定,任何環境下都能註冊
1、加了環境標識的bean,只有這個環境被激活的時候才能註冊到容器中,默認是default環境 2、加在配置類上,只有是指定的環境的時候,整個配置類裏面的所有配置才能生效 3、沒有標註環境標識的bean在任何環境下都加載
二、通過命令行參數設置虛擬機環境,並指定@Profile
1、創建一個實體類
public class BookService {
}
2、創建配置類,並註冊bean
@Configuration
public class MainConfig {
@Profile("test")
@Bean
public BookService bookService()
{
return new BookService();
}
}
3、測試
@SpringBootTest
class DemoApplicationTests {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
@Test
void contextLoads() {
BookService bean = applicationContext.getBean(BookService.class);
System.out.println(bean);
}
}
測試結果:bean並沒有被註冊。因爲@Profile指定了測試的環境,所以必須是測試環境下bean才能被註冊
我們通過在虛擬機參數位置指定-Dspring.profiles.active=xxx來指定運行環境
結果成功被註冊進來
三、在程序內設置虛擬機環境,並指定@Profile
1、創建一個需要被註冊的類
public class BookService {
}
2、配置類
@Configuration
public class MainConfig {
@Profile("test")
@Bean
public BookService bookService()
{
return new BookService();
}
}
3、在程序內設置虛擬機環境
程序內指定:
1、創建一個applicationContext
2、設置需要激活的環境,applicationContext.getEnvironment().setActiveProfiles("");
3、註冊主配置類,applicationContext.register(xxx.class)
4、啓動刷新容器,applicationContext.refresh();
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("test");
applicationContext.register(MainConfig.class);
applicationContext.refresh();
BookService bean = applicationContext.getBean(BookService.class);
System.out.println(bean);
}
}
同樣我們成功註冊了bean
四、在application.properties文件中設置虛擬環境,並指定@Profile
在application.properties文件中也可以設置虛擬機環境,然後通過@Profile指定,同樣能達到上面的效果
spring.profiles.active=test