1、啓動腳本內容:
nohup java .....省略一萬點內容.....
--spring.profiles.active=${profiles} --isJar=true >> ${logPath}/${ModuleName}.log 2>&1 &
2、在代碼中獲取spring.profiles.active的值,也就是profiles的值。可以通過如下代碼獲取數據:
String profiles = System.getenv().get("spring.profiles.active");
這個是系統級別的參數,所以如果系統還沒有啓動完成也是可以獲取的。
3、手動配置配置類
/**
* 私有構造方法
* @param flag Nothing to use
*/
private PropertiesConfiguration(boolean flag){
try{
String prefix = System.getenv().get("spring.profiles.active");
if(StringUtils.isEmpty(prefix)) {
InputStream active = PropertiesConfiguration.class
.getClassLoader().getResourceAsStream("application.properties");
Properties profile = new Properties();
profile.load(active);
prefix = profile.getProperty("spring.profiles.active");
}
InputStream inputStream = PropertiesConfiguration.class
.getClassLoader().getResourceAsStream("application-"+prefix+".properties");
Properties properties = new Properties();
properties.load(inputStream);
this.mysqlUrl = properties.getProperty("spring.datasource.mysql.url");
this.mysqlUsername = properties.getProperty("spring.datasource.mysql.username");
this.mysqlPassword = properties.getProperty("spring.datasource.mysql.password");
this.mysqlDriverClassName = properties.getProperty("spring.datasource.mysql.driverClassName");
this.mysqlFilters = properties.getProperty("spring.datasource.mysql.filters");
this.mysqlPrincipalSessionName = properties.getProperty("spring.datasource.mysql.principalSessionName");
this.oracleUrl = properties.getProperty("spring.datasource.oracle.url");
this.oracleUsername = properties.getProperty("spring.datasource.oracle.username");
this.oraclePassword = properties.getProperty("spring.datasource.oracle.password");
this.oracleDriverClassName = properties.getProperty("spring.datasource.oracle.driverClassName");
this.oracleFilters = properties.getProperty("spring.datasource.oracle.filters");
this.oraclePrincipalSessionName = properties.getProperty("spring.datasource.oracle.principalSessionName");
} catch (Exception e){
logger.error(e);
}
}
有需要全部代碼或有問題請加我私聊。
注意:
1)如果自己想用Springboot當中的application.properties或者application.yml的參數來配置相關類。必須是等待Springboot項目啓動以後,才能通過SpringContext上下文對象獲取配置參數,否則獲取的參數很有可能爲null。
2)筆者就是想手動通過自己指定配置文件來配置多環境項目,實時修改application.properties文件不太現實,所以是手動指定spring.profiles.active參數,並在項目中使用System對象獲取參數,再手動獲取配置信息。