Spring.profiles多环境配置原理

来源:互联网 发布:小米数据迁移苹果 编辑:程序博客网 时间:2024/06/07 01:43

配置项目

Spring的profiles有两个变量可以配置

  • spring.profiles.default 默认值,优先级低。当active没有配置时,使用此变量。
  • spring.profiles.active 优先级高,指定当前容器使用哪个profile

一般用法

声明多profile

如果使用spring的profiles机制,第一步要在applicationContext.xml中配置多环境实例。

 <beans profile="development">    <!-- 开发环境,具体加载bean或者properties文件 --> </beans> <beans profile="test">   <!-- 测试环境,具体加载bean或者properties文件 --> </beans>   

激活profile

在J2EE项目中,一般通过web.xml配置。

<context-param>   <param-name>spring.profiles.default</param-name>   <param-value>development</param-value></context-param>

或者

<context-param>   <param-name>spring.profiles.default</param-name>   <param-value>test</param-value></context-param>

使用java运行参数指定profiles

java运行时可以指定jvm内存参数,这个大家都知道。形式类似下面这样去指定java虚拟机启动的内存设置。

JAVA_OPTS=" -Xms1024m -Xmx1024m  -XX:PermSize=512m -XX:MaxPermSize=512m"

修改tomcat启动脚本,直接修改JAVA_OPTS:

JAVA_OPTS=" -Xms1024m -Xmx1024m  -XX:PermSize=512m -XX:MaxPermSize=512m -Dspring.profiles.active=test"

启动tomcat,发现整个系统启动时,使用profile=test的bean被激活了,证明配置生效。

JAVA 命令参数详解:

1、-D<name>=<value> set a system property  设置系统属性

可以通过System.getProperty("spring.profiles.active")获得这个值。

在虚拟机的系统属性中设置属性名/值对,运行在此虚拟机之上的应用程序可用
当虚拟机报告类找不到或类冲突时可用此参数来诊断来查看虚拟机从装入类的情况。

另外,javac -d <目录> 指定存放生成的类文件的位置

Standard System Properties

 

KeyMeaning"file.separator"Character that separates components of a file path. This is "/" on UNIX and "\" on Windows."java.class.path"Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property."java.home"Installation directory for Java Runtime Environment (JRE)"java.vendor"JRE vendor name"java.vendor.url"JRE vender URL"java.version"JRE version number"line.separator"Sequence used by operating system to separate lines in text files"os.arch"Operating system architecture"os.name"Operating system name"os.version"Operating system version"path.separator"Path separator character used in java.class.path"user.dir"User working directory"user.home"User home directory"user.name"User account name

 

 所谓的 system porperty,system 指的是 JRE (runtime)system,不是指 OS。

总结

使用java的系统参数-D方式即减轻了耦合性,也降低了开发和维护之间交流协作的部分。当有多个部署环境时,提前部署好指定的profile,这点在datasource的指定上面极为好用。



原创粉丝点击