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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章