有時候我們有多個環境,開發環境、測試環境、生產環境,每個環境都有不同的配置信息
如何用一套代碼,在不同環境上都能運行,spring的profile就是用來解決這個問題
比如想着測試環境加載一個配置類,那么這個類可以加上這個注解
一、命令行和@Profile注解用法
@Component @Profile(value="test") public class ZKWorkerClient {}
在運行jar包時只需要使用如下命令,就可以加載這個對象
java -jar *.jar -Dspring.profile.active=test
@Profile修飾類
@Configuration @Profile("prod") public class JndiDataConfig { @Bean(destroyMethod="") public DataSource dataSource() throws Exception { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } }
@Profile修飾方法
@Configuration public class AppConfig { @Bean("dataSource") @Profile("dev") public DataSource standaloneDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScript("classpath:com/bank/config/sql/schema.sql") .addScript("classpath:com/bank/config/sql/test-data.sql") .build(); } @Bean("dataSource") @Profile("prod") public DataSource jndiDataSource() throws Exception { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } }
參考:https://blog.csdn.net/loongkingwhat/article/details/105745303
二、配置多種開發環境
有時候開發是一種環境,生產又是一種環境,我們需要從配置文件靈活讀取各種參數
這時候就需要用配置文件來解決
在application.properties指定
spring.profiles.active=prod
然后再另外兩個配置文件中配置不同的參數,比如application-dev.properties
profile.url.call=http://cloudcall profile.url.workOrder=http://cloud-workorder
在寫一個config類,從properties文件里讀取
/** * @Author : wangbin * @Date : 2021/5/8 9:43 */ @ConfigurationProperties("profile.url") @Component public class BaseUrlConfig implements Serializable { private static final long serialVersionUID = 2092752356451204202L; private String call; private String workOrder; public void setCall(String call) { this.call = call; } public void setWorkOrder(String workOrder) { this.workOrder = workOrder; } public String getCall() { return call; } public String getWorkOrder() { return workOrder; } }
這時候應用讀到的就是prod配置文件里的內容了