我們在開發時,難免碰到不同環境的配置不同,比如,生產環境,測試環境,開發環境的數據庫不一樣。這樣就需要我們指定不同環境中使用不同的URL。在Spring中,我們可以創建指定環境的Bean來解決這個問題。只有當規定的profile激活時,相應的bean才會被創建。另外沒有指定profile的bean之中都會被創建,與激活哪個profile沒有關系。
package com.fgcui.config; import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile;import org.springframework.jndi.JndiObjectFactoryBean; import javax.activation.DataSource; @Configurationpublic class DataSourceConfig { @Bean(destroyMethod = "shutdown") @Profile("dev") public DataSource devDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath::schema.sql") .build(); } @Bean @Profile("prod") public DataSource prodDataSource() { JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean(); jndiObjectFactoryBean.setJndiName("jdbc/myDs"); jndiObjectFactoryBean.setResourceRef(true); jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class); return (DataSource) jndiObjectFactoryBean.getObject(); } }
那么,如何激活一個Bean呢?我們可以指定spring.profile.active屬性來指定哪個環境的bean被激活。如果不指定這個屬性,它會去找spring.profiles.default的值。
如果均沒有指定的話,就沒有激活的profile,就不會創建指定profile的bean。
有多種方式設置這個屬性:
* 作為DispatcherServlet的初始化參數
* 作為Web應用的上下文參數
* 作為環境變量
* 使用@ActiveProfiles注解設置