Maven profile整合Spring profile

本文详细介绍了如何在Maven和Spring框架(非Spring Boot)中整合profile,用于区分开发、测试和生产环境。通过Maven的profile配置在打包时替换不同环境的配置,Spring Framework通过编程或配置方式启用profile。同时,文章解决了jetty-maven-plugin在开发环境中遇到的问题,并提供了两种解决方案。对于Spring Boot项目,整合Maven profile只需简单配置即可。
摘要由CSDN通过智能技术生成

在Maven和Spring中,都有profile这个概念。profile是用于区分各种环境的,例如开发环境、测试环境、正式环境等。Maven的profile用于在打包时根据指定环境替换不同环境的配置文件配置,如数据库配置。Spring的Profile可以用于在不同的环境下加载不同的bean,例如@Profile注解。两者一个是Maven编译和打包时生效,另一个是运行时生效,默认是没有关联的,本文会分别介绍非Spring Boot项目和Spring Boot项目整合Maven profile。

Maven profile配置

pom.xml中,可以配置testproduct两个profile,分别对应测试环境和正式环境。这里也可以根据具体情况自定义。

<profiles>
  <profile>
    <id>test</id>
    ...
  </profile>
  <profile>
    <id>product</id>
    ...
  </profile>
</profiles>

此时,运行mvn package -Ptest就会使用id为test的profile内的配置打包,mvn package -Pproduct就是用来打正式环境包的命令。

Spring Framework(非Spring Boot)整合Maven profile

Spring Framework如何启用一个profile

Spring启用某个profile有多种方式(摘自官方文档:https://docs.spring.io/spring/docs/5.1.5.RELEASE/spring-framework-reference/core.html#beans-definition-profiles-enable ):

Activating a profile can be done in several ways, but the most straightforward is to do it programmatically against the Environment API which is available through an ApplicationContext.
In addition, you can also declaratively activate profiles through the spring.profiles.active property, which may be specified through system environment variables, JVM system properties, servlet context parameters in web.xml, or even as an entry in JNDI.

总结一下有以下几种方式:

  • 通过代码设置:ApplicationContext.getEnvironment().setActiveProfiles("yourProfile")
  • 通过系统环境变量spring.profiles.active值来设置
  • 通过JVM系统属性spring.profiles.active值来设置
  • 通过web.xml中的context-param来设置

为了便于跟Maven整合,我们使用web.xml来设置Spring profile,如下:

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>product</param-value>
</context-param>

以上配置会启用Spring的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值