这边文章的目的主要是为了在spring开发web项目的时候,让我们的测试,开发,生产环境的配置项
.properties作为配置文件。
我们首先需要建立一个config文件夹,然后创建开发,测试,生产环境的.properties配置项文件。

例如,dev.properties文件为开发环境,pre.properties文件为生产环境。
dev.properties配置内容为:
#test
test.username=initphp
那么,我们这个.properties文件的配置,如何打入xml文件中呢?别急,其实很简单,我们需要修改pom.xml
配置pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
xxxx.server
xxxx server
war
1.0.0
1.6
3.1.1.RELEASE
1.6.10
1.6.6
UTF-8
dev
dev
true
qa
qa
pre
pre
prod
prod
config/${env}.properties
src/main/resources
true
maven-eclipse-plugin
2.9
org.springframework.ide.eclipse.core.springnature
org.springframework.ide.eclipse.core.springbuilder
true
true
org.apache.maven.plugins
maven-compiler-plugin
2.5.1
1.6
1.6
-Xlint:all
true
true
org.codehaus.mojo
exec-maven-plugin
1.2.1
org.test.int1.Main
主要中配置了各种环境的配置项参数。中,用于读取和替换配置。
替换XML中的配置项变量,我们通过spring bean注入的方式,将配置项参数注入Config.java类中的静态变量。
例如我们主要注入到com.xxxx.xxxx.common.bo.ConfigBo,我们预先定义的一个配置类中。先看一下ConfigBo这个类:
/**
* 常量配置
* @author hanqi
*/
public class ConfigBo {
/** 每页显示页数 */
public static final int PAGE_SIZE = 20;
public static String USERNAME = ""; //被注入的static变量,不能有final终态关键字
//bean注入 USERNAME 必须要用 set函数
public void setUserName(String userName) {
USERNAME = userName;
}
}
我们需要修改xml文件,添加注入的Bean:
这个时候,我们就能在项目中,静态调用ConfigBo.USERNAME这个常量了,而不需要关心测试环境,开发环境以及正式环境的区别了。
xml中的${test.username}实际上是将properties配置文件中的选项值进行了替换,所以在mvn install后,target目录下,查看xml文件,就可以看到userName的值就是"initphp"
本文介绍了一种在Spring项目中管理不同环境(如开发、测试和生产)配置的方法。通过使用.properties文件并结合Maven插件,可以实现配置的灵活切换,并通过Spring Bean注入将配置值映射到代码中。

被折叠的 条评论
为什么被折叠?



