這篇文章主要介紹了通過(guò)實(shí)例了解Spring中@Profile的作用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
根據(jù)系統(tǒng)環(huán)境的不同,Profile可以用來(lái)切換數(shù)據(jù)源。例如切換開(kāi)發(fā),測(cè)試,生產(chǎn)環(huán)境的數(shù)據(jù)源。
舉個(gè)例子:
先創(chuàng)建配置類(lèi)MainProfileConfig:
@Configuration @PropertySource("classpath:/jdbc.properties") public class MainProfileConfig implements EmbeddedValueResolverAware { @Value("${db.user}") private String user; private String driverClass; private StringValueResolver stringValueResolver; @Profile("test") @Bean("testDataSource") public DataSource getTestDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(pwd); comboPooledDataSource.setDriverClass(driverClass); return comboPooledDataSource; } @Profile("dev") @Bean("devDataSource") public DataSource getDevDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(pwd); comboPooledDataSource.setDriverClass(driverClass); return comboPooledDataSource; } @Profile("pro") @Bean("proDataSource") public DataSource getproDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(pwd); comboPooledDataSource.setDriverClass(driverClass); return comboPooledDataSource; } @Override public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) { this.stringValueResolver = stringValueResolver; driverClass = stringValueResolver.resolveStringValue("${db.driverClass}"); } }
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站www.cdcxhl.com,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線(xiàn),公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。