Spring爲咱們提供的多環境啓動mysql
1. 配置類,注入三個不一樣環境的數據源,並加上註解spring
/** * description: 如下準備了三套不一樣環境的數據源 * * @author 70KG * @date 2018/12/17 */ @Configuration public class MyConfig { @Bean @Profile("dev") public MySqlInfo mySqlInfoDev() { MySqlInfo mySqlInfo = new MySqlInfo(); mySqlInfo.setUserName("zhangsan"); mySqlInfo.setPassWord("1111"); mySqlInfo.setDriver("com.mysql.jdbc.driver"); System.out.println("dev數據源被注入。。。。。。"); return mySqlInfo; } @Bean @Profile("test") public MySqlInfo mySqlInfoTest() { MySqlInfo mySqlInfo = new MySqlInfo(); mySqlInfo.setUserName("lisi"); mySqlInfo.setPassWord("2222"); mySqlInfo.setDriver("com.mysql.jdbc.driver"); System.out.println("test數據源被注入。。。。。。"); return mySqlInfo; } @Bean @Profile("prod") public MySqlInfo mySqlInfoProd() { MySqlInfo mySqlInfo = new MySqlInfo(); mySqlInfo.setUserName("wangwu"); mySqlInfo.setPassWord("3333"); mySqlInfo.setDriver("com.mysql.jdbc.driver"); System.out.println("prod數據源被注入。。。。。。"); return mySqlInfo; } }
2. 測試類,假設開啓生產的數據源sql
/** * description * * @author 70KG * @date 2018/12/17 */ public class Test01 { @Test public void test() { // 無參構造建立容器 AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); // 讀取配置文件,並屬性賦值 ac.register(MyConfig.class); ac.getEnvironment().setActiveProfiles("prod"); // 刷新容器 ac.refresh(); } }
3. 結果測試
prod數據源被注入。。。。。。
4. 說明spa
@Profile不只能夠加在Bean上,還能夠加在到類上,表示這個類所屬的環境code
還有一種方式讓環境生效,配置虛擬機參數,-Dspring.profiles.active=prodblog