软件开发过程一般涉及“开发 -> 测试 -> 部署上线”多个阶段,每个阶段的环境的配置参数会有不同,如数据源,文件路径等。为避免每次切换环境时都要进行参数配置等繁琐的操作,可以通过spring的profile功能来进行配置参数的切换。
以我用到的项目的实际情况为例,首先可以在resources文件夹下分别为每个环境建立单独的文件夹(也可以额外建立一个common文件夹,用于存放公共的参数配置文件),每个文件夹下面存放对应的环境所需的配置文件,就像这样子:

在resources文件夹下建立applicationContext-profile.xml文件,用来定义不同的profile:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd">
<description>spring profile配置</description>
<!-- 开发环境配置文件 -->
<beans profile="developmen

本文介绍了如何使用Spring的profile功能进行环境配置切换,以适应开发、测试和部署的不同阶段。通过在resources文件夹下创建不同环境的配置文件,并利用applicationContext-profile.xml定义profile,再结合spring.profiles.default和spring.profiles.active属性激活所需环境。设置方式包括web.xml、JNDI、环境变量、JVM参数和@ActiveProfiles注解。文中还展示了如何在程序中使用@Profile注解控制bean的创建,特别是切换数据源的例子。
最低0.47元/天 解锁文章
631

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



