spring profiles + maven profiles 整合

spring profiles + maven profiles 整合

  • 在maven中配置profiles,
<build>
        <!-- 這個是打包的時候生成的名字,每個項目都需要另外設置 -->
        <finalName>web</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*.xml</include>
                    <include>*.properties</include>
                    <include>*.txt</include>
                </includes>
                <excludes>
                    <exclude>test/*</exclude>
                    <exclude>production/*</exclude>
                    <exclude>development/*</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources/${profiles.active}</directory>
            </resource>

            <resource>
                <directory>src/main/webapp/WEB-INF</directory>
                <includes>
                    <include>*.xml</include>
                    <include>*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins><!--使用到的插件 -->
            <plugin><!--編譯插件 -->
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>buildnumber-maven-plugin</artifactId>
                <version>1.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>create-timestamp</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <format>{0,date,yyyyMMddHHmmss}</format>
                    <items>
                        <item>timestamp</item>
                    </items>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                        <manifestEntries>
                            <App-Version-static>${timestamp}</App-Version-static>
                        </manifestEntries>
                    </archive>



                    <!-- 使用 mvn clean package -Ptest 時,會將maven中定義的properties替換web.xml中的佔位符 -->
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                    <webResources>
                        <resource>
                            <directory>src/main/webapp/WEB-INF</directory>
                            <filtering>true</filtering>
                            <excludes>
                                <exclude>template/**</exclude>
                            </excludes>
                            <targetPath>WEB-INF</targetPath>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>

            <!-- <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    http://maven.apache.org/plugins/maven-war-plugin/
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                    <webResources>
                        <resource>
                            元配置文件的目錄,相對於pom.xml文件的路徑
                            <directory>src/main/webapp/WEB-INF</directory>
                            是否過濾文件,也就是是否啓動auto-config的功能
                            <filtering>true</filtering>
                            不包括以下文件夾下的文件
                            <excludes>
                                <exclude>template/**</exclude>
                            </excludes>
                            <targetPath>WEB-INF</targetPath>
                        </resource>
                    </webResources>
                </configuration>
            </plugin> -->
        </plugins>
        <defaultGoal>compile</defaultGoal>
    </build>


    <profiles>
        <profile>
            <!-- 生產環境 -->
            <id>production</id>
            <properties>
                <profiles.active>production</profiles.active>
            </properties>
        </profile>
        <profile>
            <!-- 本地開發環境 -->
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 測試環境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
        </profile>
    </profiles>
  • 在src/main/resources目錄下添加環境目錄

添加開發環境的目錄 dev,並將properties配置文件放按目錄結構放到該目錄中。

添加測試環境的目錄 test,並將properties配置文件放按目錄結構放到該目錄中。

添加生產環境的目錄 production,並將properties配置文件放按目錄結構放到該目錄中。

web 這裏需要注意,這個是打包的時候生成的名字,每個項目都需要另外設置。

  • 在spring配置文件中配置profiles
<!-- 自動掃描(自動注入) -->
    <context:component-scan base-package="com.web">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <beans>
        <bean
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations"> <!-- PropertyPlaceholderConfigurer類中有個locations屬性,接收的是一個數組,即我們可以在下面配好多個properties文件 -->
                <array>
                    <value>classpath:conf/d.properties</value>
                </array>
            </property>
            <property name="order" value="1"></property>
            <property name="ignoreUnresolvablePlaceholders" value="true" />   
        </bean>
    </beans>
    <beans profile="dev">
        <bean
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations"> <!-- PropertyPlaceholderConfigurer類中有個locations屬性,接收的是一個數組,即我們可以在下面配好多個properties文件 -->
                <array>
                    <value>classpath:conf/config.properties</value>
                </array>
            </property>
            <property name="order" value="2"></property>
            <property name="ignoreUnresolvablePlaceholders" value="true" />   
        </bean>
    </beans>

    <beans profile="test">
        <bean
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations"> <!-- PropertyPlaceholderConfigurer類中有個locations屬性,接收的是一個數組,即我們可以在下面配好多個properties文件 -->
                <array>
                    <value>file:/Users/saleson/Desktop/config5.properties</value>
                </array>
            </property>
            <property name="order" value="2"></property>
            <property name="ignoreUnresolvablePlaceholders" value="true" />   
        </bean>
    </beans>

    <beans>
        <bean id="personService" class="com.web.service.impl.PersonServiceImpl">
            <property name="person">
                <bean class="com.web.beans.Person">
                    <property name="name">
                        <value>${person.name}</value>
                    </property>
                    <property name="age" value="${person.age}" />
                </bean>
            </property>
        </bean>
    </beans>

org.springframework.beans.factory.config.PropertyPlaceholderConfigurer配置中必須要加上order屬性和ignoreUnresolvablePlaceholders屬性,不然不能加載多個properties文件。

對應不周的環境,在beans節點中設置不同的profiles的屬性值,在這裏我只設置dev環境和test環境的。

  • 配置web.xml
<context-param>  
    <param-name>spring.profiles.active</param-name> 
    <param-value>dev</param-value>
</context-param>  

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

到這一步spring環境配置和maven的環境配置就分別完成了,但是這個時候spring profiles 和 maven profiles還不能結合在一起使用。 如果要將之整合在一起,還得做一些調整,請看下面。

  • 新建一個SpringLoaderListener類,繼承org.springframework.web.context.ContextLoaderListener,代碼如下:
package com.web.listener;

import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.ContextLoaderListener;

public class SpringLoaderListener extends ContextLoaderListener{

    private String propertiesPath = "conf/d.properties";

    @Override
    public void contextInitialized(ServletContextEvent event) {
        loadEnvironment(event);
        super.contextInitialized(event);
    }


    /**
     * 加載啓動環境
     * @param event
     */
    private void loadEnvironment(ServletContextEvent event){
        String springProfileActive = event.getServletContext().getInitParameter("spring.profiles.active");
        if("${profiles.active}".equals(springProfileActive)){
            String profilesAcive = "test";
            String profilesactiveKey = "profiles.active";
            Properties properties = new Properties();
            try {
                properties.load(new ClassPathResource(propertiesPath).getInputStream());
                profilesAcive = properties.getProperty(profilesactiveKey, profilesAcive);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.getProperties().setProperty(profilesactiveKey, profilesAcive);
        }
    }
}

xml 也需要調整

<context-param>  
    <param-name>spring.profiles.active</param-name>  
  <param-value>${profiles.active}</param-value>  
        <!-- <param-value>dev</param-value>  -->
</context-param>  
<listener>
    <listener-class>com.web.listener.SpringLoaderListener</listener-class>
</listener>

到這裏,spring profiles眼maven profiles就整合在一起了。

使用maven的profiles進行控制,在項目上右鍵選擇Maven -> Select Maven Profiles,然後再選擇對應的環境。

在使用maven進行導出時,使用maven命令,比如導出測試環境的war包:mvc clean package -Ptest

導出的war包中中web.xml中spring.profiles.active的屬性值就變成了test。
完整的web.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">



    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-core.xml</param-value>
    </context-param>

    <context-param>  
        <param-name>spring.profiles.active</param-name>  
        <param-value>test</param-value>  
        <!-- <param-value>dev</param-value>  -->
    </context-param>  

    <!-- 多項目部署到同一Tomcat中且都使用了log4j -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webName.root.web</param-value>
    </context-param>

    <!-- <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> -->
    <listener>
        <listener-class>com.web.listener.SpringLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <filter>
        <description>字符集過濾器</description>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <description>字符集編碼</description>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
發佈了40 篇原創文章 · 獲贊 19 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章