spring profiles + maven profiles 整合

spring profiles + maven profiles 整合

  • 在maven中配置profiles,
<build>
        
        <finalName>webfinalName>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>*.xmlinclude>
                    <include>*.propertiesinclude>
                    <include>*.txtinclude>
                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-INFdirectory>
                <includes>
                    <include>*.xmlinclude>
                    <include>*.propertiesinclude>
                includes>
            resource>
        resources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.7source>
                    <target>1.7target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.felixgroupId>
                <artifactId>maven-bundle-pluginartifactId>
                <extensions>trueextensions>
            plugin>
            <plugin>
                <groupId>org.codehaus.mojogroupId>
                <artifactId>buildnumber-maven-pluginartifactId>
                <version>1.3version>
                <executions>
                    <execution>
                        <phase>packagephase>
                        <goals>
                            <goal>create-timestampgoal>
                        goals>
                    execution>
                executions>
                <configuration>
                    <format>{0,date,yyyyMMddHHmmss}format>
                    <items>
                        <item>timestampitem>
                    items>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-war-pluginartifactId>
                <version>2.3version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>trueaddDefaultImplementationEntries>
                        manifest>
                        <manifestEntries>
                            <App-Version-static>${timestamp}App-Version-static>
                        manifestEntries>
                    archive>



                    
                    <webXml>src/main/webapp/WEB-INF/web.xmlwebXml>
                    <webResources>
                        <resource>
                            <directory>src/main/webapp/WEB-INFdirectory>
                            <filtering>truefiltering>
                            <excludes>
                                <exclude>template/**exclude>
                            excludes>
                            <targetPath>WEB-INFtargetPath>
                        resource>
                    webResources>
                configuration>
            plugin>

            
        plugins>
        <defaultGoal>compiledefaultGoal>
    build>


    <profiles>
        <profile>
            
            <id>productionid>
            <properties>
                <profiles.active>productionprofiles.active>
            properties>
        profile>
        <profile>
            
            <id>devid>
            <properties>
                <profiles.active>devprofiles.active>
            properties>
            <activation>
                <activeByDefault>trueactiveByDefault>
            activation>
        profile>
        <profile>
            
            <id>testid>
            <properties>
                <profiles.active>testprofiles.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"> 
                <array>
                    <value>classpath:conf/d.propertiesvalue>
                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"> 
                <array>
                    <value>classpath:conf/config.propertiesvalue>
                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"> 
                <array>
                    <value>file:/Users/saleson/Desktop/config5.propertiesvalue>
                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.activeparam-name> 
    <param-value>devparam-value>
context-param>  

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-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.activeparam-name>  
  <param-value>${profiles.active}param-value>  
        
context-param>  
<listener>
    <listener-class>com.web.listener.SpringLoaderListenerlistener-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如下:


<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>contextConfigLocationparam-name>
        <param-value>classpath:spring/spring-core.xmlparam-value>
    context-param>

    <context-param>  
        <param-name>spring.profiles.activeparam-name>  
        <param-value>testparam-value>  
        
    context-param>  

    
    <context-param>
        <param-name>webAppRootKeyparam-name>
        <param-value>webName.root.webparam-value>
    context-param>

    
    <listener>
        <listener-class>com.web.listener.SpringLoaderListenerlistener-class>
    listener>

    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>

    <filter>
        <description>字符集过滤器description>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <async-supported>trueasync-supported>
        <init-param>
            <description>字符集编码description>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>

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

    <servlet>
        <servlet-name>spring-mvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <description>spring mvc 配置文件description>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>

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

web-app>

你可能感兴趣的:(架构设计)