javascript
Spring Profile模式示例
此概念是針對(duì)不同部署環(huán)境的輕松配置區(qū)分符。
直接的用例(已提出)是對(duì)相關(guān)類進(jìn)行注釋,以便Spring根據(jù)活動(dòng)的配置文件加載適當(dāng)?shù)念悺?
但是,這種方法可能并不總是適用于常見的用例……通常,配置密鑰是相同的,并且僅值會(huì)隨環(huán)境而變化。
在本文中,我想提出一種模式來支持按環(huán)境加載配置數(shù)據(jù), 而無需為每個(gè)概要文件(即針對(duì)每個(gè)環(huán)境)創(chuàng)建/維護(hù)多個(gè)類。
在整個(gè)文章中,假設(shè)每個(gè)部署環(huán)境的數(shù)據(jù)庫定義(例如用戶名或連接URL)不同,我將以數(shù)據(jù)庫連接配置為例。
主要思想是使用一個(gè)類來加載配置(即,一個(gè)類用于數(shù)據(jù)庫連接定義),然后將包含正確概要文件配置數(shù)據(jù)的適當(dāng)實(shí)例注入其中。
為了方便和清楚起見,該過程分為三個(gè)階段:
階段1 :基礎(chǔ)設(shè)施
步驟1.1 –創(chuàng)建一個(gè)包含所有配置數(shù)據(jù)的屬性文件
步驟1.2 –為每個(gè)配置文件創(chuàng)建注釋 步驟1.3 –確保在上下文加載期間加載了配置文件
階段2 :實(shí)施配置文件模式
步驟2.1 –創(chuàng)建屬性界面
步驟2.2 –為每個(gè)配置文件創(chuàng)建一個(gè)類 步驟2.3 –創(chuàng)建一個(gè)包含所有數(shù)據(jù)的抽象文件
階段3 :使用模式
步驟3.1 –使用模式的示例
彈簧輪廓圖–階段1:基礎(chǔ)準(zhǔn)備
該階段將建立使用Spring Profile和配置文件的初始基礎(chǔ)設(shè)施。
步驟1.1 –創(chuàng)建一個(gè)包含所有配置數(shù)據(jù)的屬性文件
假設(shè)您有一個(gè)maven風(fēng)格的項(xiàng)目,請(qǐng)?jiān)趕rc / main / resources / properties中為每個(gè)環(huán)境創(chuàng)建一個(gè)文件,例如:
my_company_dev.properties
my_company_test.properties
my_company_production.properties
my_company_dev.properties內(nèi)容的示例:
jdbc.url = jdbc:mysql:// localhost:3306 / my_project_db
db.username = dev1
db.password = dev1 hibernate.show_sql = true
my_company_production.properties內(nèi)容的示例:
jdbc.url = jdbc:mysql://10.26.26.26:3306 / my_project_db
db.username = prod1
db.password = fdasjkladsof8aualwnlulw344uwj9l34 hibernate.show_sql = false
步驟1.2 –為每個(gè)配置文件創(chuàng)建注釋
在src.main.java.com.mycompany.annotation中為每個(gè)Profile創(chuàng)建注釋,例如:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile("DEV") public @interface Dev { }@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile("PRODUCTION") public @interface Production { } 為每個(gè)配置文件創(chuàng)建一個(gè)枚舉:
公共接口MyEnums {
步驟1.3 –確保在上下文加載期間加載了配置文件
- 定義一個(gè)系統(tǒng)變量以指示代碼在哪個(gè)環(huán)境中運(yùn)行。
在Tomcat中,轉(zhuǎn)到$ {tomcat.di} /conf/catalina.properties并插入一行:
profile = DEV(根據(jù)您的環(huán)境) - 定義一個(gè)類別以設(shè)置活動(dòng)配置文件 public class ConfigurableApplicationContextInitializer implementsApplicationContextInitializer<configurableapplicationcontext> {@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {String profile = System.getProperty("profile");if (profile==null || profile.equalsIgnoreCase(Profile.DEV.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.DEV.name()); }else if(profile.equalsIgnoreCase(Profile.PRODUCTION.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.PRODUCTION.name()); }else if(profile.equalsIgnoreCase(Profile.TEST.name())){applicationContext.getEnvironment().setActiveProfiles(Profile.TEST.name()); }} }
- 確保在上下文加載期間加載了該類
在項(xiàng)目web.xml中,插入以下內(nèi)容: <context-param><param-name>contextInitializerClasses</param-name><param-value>com.matomy.conf.ConfigurableApplicationContextInitializer</param-value> </context-param>
階段2:實(shí)施配置文件模式
此階段利用我們之前構(gòu)建的基礎(chǔ)架構(gòu)并實(shí)現(xiàn)配置文件模式。
步驟2.1 –創(chuàng)建屬性界面
為您擁有的配置數(shù)據(jù)創(chuàng)建一個(gè)接口。
在我們的例子中,該接口將提供對(duì)四個(gè)配置數(shù)據(jù)項(xiàng)的訪問。 所以看起來像這樣:
步驟2.2 –為每個(gè)配置文件創(chuàng)建一個(gè)類
開發(fā)配置文件示例:
@Dev //Notice the dev annotation @Component("systemStrings") public class SystemStringsDevImpl extends AbstractSystemStrings implements SystemStrings{public SystemStringsDevImpl() throws IOException {//indication on the relevant properties filesuper("/properties/my_company_dev.properties");} }生產(chǎn)資料示例:
@Prouction //Notice the production annotation @Component("systemStrings") public class SystemStringsProductionImpl extends AbstractSystemStrings implements SystemStrings{public SystemStringsProductionImpl() throws IOException {//indication on the relevant properties filesuper("/properties/my_company_production.properties");} }上面的兩個(gè)類是屬性文件和相關(guān)環(huán)境之間進(jìn)行綁定的位置。
您可能已經(jīng)注意到,這些類擴(kuò)展了一個(gè)抽象類。 這項(xiàng)技術(shù)很有用,因此我們不需要為每個(gè)Profile定義每個(gè)getter,從長(zhǎng)遠(yuǎn)來看,這是無法管理的,實(shí)際上,這樣做是沒有意義的。
蜜糖和蜂蜜位于下一步,其中定義了抽象類。
步驟2.3 –創(chuàng)建一個(gè)包含所有數(shù)據(jù)的抽象文件
public abstract class AbstractSystemStrings implements SystemStrings{//Variables as in configuration properties file private String jdbcUrl; private String dBUsername; private String dBPassword; private boolean hibernateShowSQL;public AbstractSystemStrings(String activePropertiesFile) throws IOException {//option to override project configuration from externalFileloadConfigurationFromExternalFile();//optional..//load relevant propertiesloadProjectConfigurationPerEnvironment(activePropertiesFile); }private void loadProjectConfigurationPerEnvironment(String activePropertiesFile) throws IOException {Resource[] resources = new ClassPathResource[ ] { new ClassPathResource( activePropertiesFile ) };Properties props = null;props = PropertiesLoaderUtils.loadProperties(resources[0]);jdbcUrl = props.getProperty("jdbc.url");dBUsername = props.getProperty("db.username"); dBPassword = props.getProperty("db.password");hibernateShowSQL = new Boolean(props.getProperty("hibernate.show_sql")); }//here should come the interface getters....階段3:使用模式
您可能還記得,在前面的步驟中,我們定義了一個(gè)配置數(shù)據(jù)接口。
現(xiàn)在,我們將在一個(gè)類中使用該接口 ,該類每個(gè)環(huán)境需要不同的數(shù)據(jù)。
請(qǐng)注意,這個(gè)例子與Spring博客的例子有著關(guān)鍵的區(qū)別,因?yàn)楝F(xiàn)在我們不需要為每個(gè)概要文件創(chuàng)建一個(gè)類 ,因?yàn)樵谶@種情況下我們?cè)诟乓募惺褂孟嗤姆椒ú⑶?strong>僅改變數(shù)據(jù) 。
步驟3.1 –使用模式的示例
@Configuration @EnableTransactionManagement //DB connection configuration class //(don't tell me you're still using xml... ;-) public class PersistenceConfig {@Autowiredprivate SystemStrings systemStrings; //Spring will wire by active profile@Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){LocalContainerEntityManagerFactoryBean factoryBean= new LocalContainerEntityManagerFactoryBean();factoryBean.setDataSource( dataSource() );factoryBean.setPersistenceUnitName("my_pu"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){{// JPA propertiesthis.setDatabase( Database.MYSQL); this.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt.. }}; factoryBean.setJpaVendorAdapter( vendorAdapter );factoryBean.setJpaProperties( additionalProperties() );return factoryBean;} //... @Beanpublic ComboPooledDataSource dataSource(){ComboPooledDataSource poolDataSource = new ComboPooledDataSource();try {poolDataSource.setDriverClass( systemStrings.getDriverClassNameMngHibernate() );} catch (PropertyVetoException e) {e.printStackTrace();} //is set per environemnt..poolDataSource.setJdbcUrl(systemStrings.getJdbcUrl());poolDataSource.setUser( systemStrings.getDBUsername() );poolDataSource.setPassword( systemStrings.getDBPassword() );//.. more properties... return poolDataSource;} } 我將不勝感激和改進(jìn)。
請(qǐng)享用!
參考: Gal Levinsky博客博客中來自JCG合作伙伴 Gal Levinsky的Spring Profile模式 。
翻譯自: https://www.javacodegeeks.com/2012/08/spring-profile-pattern-example_7.html
總結(jié)
以上是生活随笔為你收集整理的Spring Profile模式示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pr拉帧快捷键(pr加帧快捷键)
- 下一篇: 使用Spring 3 MVC处理表单验证