@Profile 註解:
1.使用@Profile的原因
在平時的開發中,通常開發一個開發庫,測試一個測試庫,生產一個生產庫。
我們將數據庫信息寫在一個配置文件中,在部署的時候我們將配置文件改成對應的配置文件,這樣改來改去非常麻煩。
在使用@Profile後,我們就可以定義3個配置文件dev、sit、pro其分別對應3個profile,在實際運行的時候只需給定一個參數,容器就會加載激活的配置文件,這樣就簡便了。
2.使用實戰
(1)測試bean
public class TestBean {
private String content;
public TestBean(String content) {
super();
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
(2)測試配置
@Configuration
public class TestConfig {
@Bean
@Profile("dev")
public TestBean devTestBean() {
return new TestBean("from development profile");
}
@Bean
@Profile("pro")
public TestBean proTestBean() {
return new TestBean("from production profile");
}
}
(3)測試
@RunWith(SpringJUnit4ClassRunner.class)
//在SpringJUnit4ClassRunner在JUnit環境下提供Spring TestContext Framework功能
@ContextConfiguration(classes={TestConfig.class}) //加載配置ApplicationContext,classes屬性用來加載類
@ActiveProfiles("pro")//聲明活動的profile
public class DemoBeanIntegrationTests {
@Autowired
private TestBean testBean;
@Test
public void prodBeanShouldInject() {
String expected="from production profile";
String actual=testBean.getContent();
Assert.assertEquals(expected, actual);
}
}
3.測試結果
(1)@ActiveProfiles(“pro”)測試
(2)@ActiveProfiles(“dev”)測試
項目代碼地址–碼雲
一名初學者如有問題歡迎指正。