maven下多環境配置文件、屬性管理 & Spring使用@value初始化字段值

說明一下,很多項目把配置文件與項目偶合在一起,比如與第三方的各種私密配置信息都與項目耦合在一起,導致什麼結果,任何一個該項目的開發人員都能知道生產環境的各種配置,而且開發人員離職後一般都會把項目copy在自己的硬盤上,各種私密的配置信息很容易泄露。

好的架構,會把配置文件從項目中解耦,配置文件由各自不同的人員維護(開發環境有開發者維護,測試和生產由運維維護),生產的必須有運維專業人員操作和讀取。做法有很多,不就是要讀取指定位置的配置文件麼。可以這麼做,一個專門管理配置文件的插件config,config對外提供api,api使用@Component,一個配置文件定義一個javabean,在項目啓動初始化的時候xml轉java,項目中其它位置想讀取配置時引用config插件。配置文件可以放在任何地方,遠程或本地,可能放在服務器(tomcat)所在根目錄的一個位置/var/項目名稱/config/。

好開始正題
這是一個maven項目
使用spring的@value注入屬性,@value 指定的值在env.properties中
方法一:屬性配置文件的全量替換,使用maven的copy命令
建議先看方法二

// step 1 這樣一個類
@Service("commonService")
public class CommonService implements org.springframework.beans.factory.InitializingBean{
    @Value("${account.source}")
    private String source;
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化完成");
    }
}
// step 2 
//src/main/resources下有一個配置文件env.properties,文件內容如下
account.source=123456
//step 3
/*
src/main/filters 下有3個配置文件dev.properties,uat.properties,prd.properties,文件內容都是
account.source=wqeir231234
*/

maven自帶屬性 http://www.xuebuyuan.com/2038385.html

//step 4
//項目的pom.xml中有 主要使用了copy命令-文件全量copy
<profiles>
        <profile>
            <id>local</id>
            <properties>
                <env>local</env>
                <env.overwrite>false</env.overwrite>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
                <env.overwrite>true</env.overwrite>
            </properties>
        </profile>
        <profile>
            <id>uat</id>
            <properties>
                <env>uat</env>
                <env.overwrite>true</env.overwrite>
            </properties>
        </profile>
        <profile>
            <id>prd</id>
            <properties>
                <env>prd</env>
                <env.overwrite>true</env.overwrite>
            </properties>
        </profile>
    </profiles>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <!--<phase>generate-sources</phase>-->
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <!--<target >-->
                            <!--<echo message="開始拷貝${env}環境配置文件" />-->
                            <!--</target>-->

                            <target name="env-target" if="${env.overwrite}">
                                <!--<delete file="${basedir}/target/classes/env.properties" verbose="true" deleteonexit="true"/>-->
                                <echo message="開始拷貝${env}環境配置文件:從${basedir}/src/main/filters/${env}.properties 拷貝到 ${basedir}/target/classes/env.properties" />
                                <copy file="${basedir}/src/main/filters/${env}.properties" tofile="${basedir}/target/classes/env.properties" overwrite="true" force="true"/>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>      
        </plugins>
    </build>

方法一完成

方法二

// step 1 這樣一個類
@Service("commonService")
public class CommonService implements org.springframework.beans.factory.InitializingBean{
    @Value("${account.source}")
    private String source;
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化完成");
    }
}
// step 2 這兒所有變量都使用${變量名}作爲佔位符,maven在構建的時候替換爲真正的值
//src/main/resources目錄或子目錄下有多個配置文件
//文件一 env.properties,文件內容如下
account.source=${account.source}
/*
文件二 src/main/resources/spring下有applicationContext.xml、applicationContext-shiro.xml、spring-mvc.xml等,其中內容分別是
*/
jdbcUrl=${jdbcUrl}
shiro_loginUrl=${shiroLoginUrl}
cache=${cache}
//step 3
/*
src/main/filters 下有3個配置文件dev.properties,uat.properties,product.properties,文件內容都是
account.source=wqeir231234
jdbcUrl=www.baidu.com/mysql
shiro_loginUrl=www.baidu.com/login
cache=www.baidu.com/cache
*/
//step 4 pom.xml主要內容與方法一的不同
<!-- 在maven構建的時候 選擇其中一個<id>xx</id>,不選擇則使用默認的,由<activeByDefault>true</activeByDefault>指定 -->
 <!-- 使用<properties>可以在pom中隨便自定義變量 -->
<profiles>
    <profile>
        <id>dev</id>
        <!-- 自定義變量 env 值爲dev -->
        <properties>
            <env>dev</env>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>sit</id>
        <!-- 自定義變量 sit 值爲sit -->
        <properties>
            <env>sit</env>
        </properties>
    </profile>
    <profile>
        <id>uat</id>
        <!-- 自定義變量 uat 值爲uat -->
        <properties>
            <env>uat</env>
        </properties>
    </profile>
    <profile>
        <id>product</id>
        <!-- 自定義變量 product 值爲product -->
        <properties>
            <env>product</env>
        </properties>
    </profile>
</profiles>

<build>
    <!-- java源文件 ,標準的maven項目目錄包含src/mainjava src/main/resource src/main/filters src/main/test-->
    <sourceDirectory>src/main/java</sourceDirectory>
    <!-- 多環境配置文件 ${env} env是上面自定義的變量 -->
    <!-- 取這一個環境的配置文件作爲過濾文件-->
    <filters>
        <filter>src/main/filters/${env}.properties</filter>
    </filters>
    <resources>
        <!-- 定義資源 -->
        <resource>
            <!-- 指定資源所在目錄(配置文件,比如spring/springmvc等等)文件目錄 -->
            <directory>src/main/resources</directory>
            <!-- 包括配置文件下所有的子目錄 -->
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
        <!-- 定義資源二 -->
        <resource>
            <directory>src/main/resources</directory>
            <!-- 這個資源包括所有目錄的xml文件和properties文件 -->
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <!-- 對這個資源包含的文件使用上面的過濾文件過濾 把這個${xxx}替換爲真實的值 -->
            <filtering>true</filtering>
        </resource>
    </resources>
    <!-- 構建完成文件輸出位置-->
    <outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
    <plugins>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.26</version>
            <configuration>
                <connectors>
                    <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                        <port>80</port>
                        <maxIdleTime>60000</maxIdleTime>
                    </connector>
                </connectors>
                <webAppConfig>
                    <defaultsDescriptor>src/main/resources/webdefault.xml</defaultsDescriptor>
                </webAppConfig>
                <stopPort>9966</stopPort>
                <stopKey>jetty-stop</stopKey>
                <scanIntervalSeconds>10</scanIntervalSeconds>
            </configuration>
        </plugin>
    </plugins>
</build>

完成
eclipse中執行maven構建命令
右擊工程,選擇”Debug As”或”Run As”,再選擇”Maven build”
在Goals中輸入compile
Profiles輸入dev或sit或product
maven常用命令http://blog.csdn.net/u011939453/article/details/43017865

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章