1.开发的时候经常需要加载不同的环境,比如本地开发环境dev,生产环境product。如果需要手动去修改的话就太麻烦了,自己实现了maven资源替换,然后多环境下的配置文件管理的demo,在此贴出来。
2.实现需求:
根据本地or开发配置文件,加载不同的配置,如果使用本地数据库demodb,zhangsan,123456才能登录成功;
如果使用生产环境数据库productdb,wangwu,123455才能登录成功;
代码如下:
1.父项目myssm-pom下两套配置,dev.properties为本地开发配置,product.properties为生产环境配置;
dev.properties:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/demodb username=root password=root
product.properties:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/productdb username=root password=root
2.myssm-pom.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cy.myssm</groupId> <artifactId>myssm-pom</artifactId> <version>1.0.0</version> <modules> <module>../myssm-web</module> <module>../myssm-service</module> <module>../myssm-dao</module> <module>../myssm-support</module> </modules> <packaging>pom</packaging> <!-- 环境配置 --> <profiles> <!-- 本地环境 --> <profile> <id>dev</id> <activation> <!-- 默认激活dev --> <activeByDefault>true</activeByDefault> </activation> <build> <!-- 指定当前profile环境下,属性文件路径 --> <filters> <filter>../${project.parent.artifactId}/properties/dev.properties</filter> </filters> </build> </profile> <!-- 生产环境 --> <profile> <id>product</id> <build> <filters> <filter>../${project.parent.artifactId}/properties/product.properties</filter> </filters> </build> </profile> </profiles> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <useDefaultDelimiters>false</useDefaultDelimiters> <delimiters> <delimiter>$[*]</delimiter> </delimiters> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> <resources> <resource> <!-- 要替换属性的文件目录 --> <directory>${basedir}/src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </project>