本文主要是介绍传统java项目根据环境使用多配制文件策略,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 传统java项目根据环境使用多配制文件策略
- 配置
- 创建配置文件
- 修改web.xml
- 修改配置读取方式
- 运行
- 开发环境
- 新增
- 生产环境
传统java项目根据环境使用多配制文件策略
本项目非maven和springboot项目,以前的旧项目jar放在lib下的那一种
项目环境为:spring mvc 4.0.0,使用spring Profiles 完成
Spring官网介绍
配置
创建配置文件
修改web.xml
以下几项必备
<!-- 可以获取项目的绝对路径 -->
<context-param><param-name>webAppRootKey</param-name><param-value>jsjyjd.root</param-value>
</context-param>
<!--默认profile为pro, 可以通过启动加参数修改-Dspring.profiles.active=dev-->
<context-param><param-name>spring.profiles.default</param-name><param-value>pro</param-value>
</context-param>
<!-- log4j config path -->
<context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:${spring.profiles.default}/log4j.properties</param-value>
</context-param>
<listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
修改配置读取方式
新建一个xml,必须新建一个,里面只能写环境相关的东西,写在其他已经存在的文件中会报错(我是这样)
spring-custom.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsd"><!-- 开发配置文件--><beans profile="dev"><!-- spring的属性加载器,加载properties文件中的属性 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:dev/sys.properties</value><value>classpath:dev/redis.properties</value><value>classpath:dev/jdbc.properties</value></list></property></bean></beans><!-- 生产配置文件--><beans profile="pro"><!-- spring的属性加载器,加载properties文件中的属性 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:pro/sys.properties</value><value>classpath:pro/redis.properties</value><value>classpath:pro/jdbc.properties</value></list></property></bean></beans>
</beans>
- 在其他文件中(spring-mvc.xml)导入 spring-custom.xml
<import resource="spring-custom.xml"/>
3. 配置已经完成了,直接打包运行的话已经可以识别到pro环境中的配置了
运行
开发环境
添加JVM运行参数,启动后就可以使用dev的环境
-Dspring.profiles.active=dev
新增
2021/04/22 新增,linux开发环境下会有问题
在启动命令里加上两条命令
-Dspring.profiles.active=dev
-Dspring.profiles.default=dev
生产环境
没什么要调整的,直接打包就行了
这篇关于传统java项目根据环境使用多配制文件策略的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!