概述
一个项目可能会有不同的环境,例如dev/stating/prod等,不同的环境的配置文件是不同的,如何根据环境快速的切换到对应的配置文件很重要。
在maven和 spring中都有一个profile的概念,下面分别说
1. 在maven中的pom文件中的profile的作用是根据不同的环境将对应的环境变量设置到项目中,如下例子
步骤一:在pom文件中写profile
<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<!-- 设置默认激活这个配置 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 发布环境 -->
<id>release</id>
<properties>
<profiles.active>release</profiles.active>
</properties>
</profile>
<profile>
<!-- 测试环境 -->
<id>beta</id>
<properties>
<profiles.active>beta</profiles.active>
</properties>
</profile>
</profiles>
步骤二:设置 resources的位置和filtering为true
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
filtering属性为true时,主要用来替换项目中资源文件(.xml、.properties)当中由 ${...} 标记的变量
步骤三:激活profile
以下两种方式可以激活:
a. mvn package时使用-P参数来指定profile,例如mvn package -P dev,这样就会把dev 这个profile中的变量设置到项目对应的变量里面,通常是通过${}和@@来注入属性
b.在对应的profile标签里面写入如下标签,代表默认激活的profile <activeByDefault>true</activeByDefault>
2. spring中的profile
Spring中有个注解叫做@Profile("dev"),这个注解只有在对应的profile激活才能使用,这个profile和上面的maven中的没关系,可以通过如下方式激活
一、启动Java应用时,通过-D传入系统参数
- -Dspring.profiles.active=dev
二、如果是web环境,可以通过上下文初始化参数设置
- <context-param>
- <param-name>spring.profiles.active</param-name>
- <param-value>dev</param-value>
- </context-param>
三 、通过自定义添加PropertySource
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("spring.profiles.active", "dev");
- MapPropertySource propertySource = new MapPropertySource("map", map);
- env.getPropertySources().addFirst(propertySource);
四、直接设置Profile
- env.setActiveProfiles("dev", "test");
四、通过操作系统的环境变量来激活
- 在Spring Boot项目中,如果事先在OS环境变量中定义了“SPRING_PROFILES_ACTIVE”,则会采用此处定义的配置文件
以上方式都可以设置多个profile,多个之间通过如逗号/分号等分隔。
最后
以上就是如意小熊猫为你收集整理的maven的profile功能2. spring中的profile的全部内容,希望文章能够帮你解决maven的profile功能2. spring中的profile所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复