Spring Profiles使用方法详解

目录
  • Spring Profiles
    • bean使用profile注解
    • XML声明profile
    • 设置profile
      • WebApplicationInitializer 接口
      • ConfigurableEnvironment 接口
      • Web.xml
      • JVM 设置
      • 系统环境变量
      • Maven设置
      • Profiles In Test
    • 默认Profile
    • 获取生效的Profiles
    • 使用Environment
    • 使用spring.profiles.active
  • SpringBoot Profiles
    • 设置Profiles
    • Profile-specific Properties Files
    • 单文件配置
    • Profile Group

Spring Profiles

今天学习下,Spring的核心功能之一 profiles,该特性允许开发者将beans映射到不同的环境中,如dev、test、prod。开发者启动服务时,可以根据自身需要在不同的环境中激活不同的配置。

bean使用profile注解

先来学习一个最简单profle的使用方式,学习如何让bean属于特定的环境。假设一个场景:一个普通的bean,只在开发期间有效,其他环境无效。

@Component
@Profile("dev")
public class DevDatasourceConfig{
}

如上述代码,只需要在声明bean时,配合@Profile注解,并指定特定的环境即可。根据上面的场景,反过来看:假设一个bean除了在开发期间无效,在其他环境(如test、prod)有效。@Profile支持NOT操作,只需要在前面加上 ! 符号。例如 !dev, 就可以将dev环境排除。

@Component
@Profile("!dev")
// @Profile(value={"dev & local"})
public class DevDatasourceConfig{
}

XML声明profile

在XML配置文件中也可以配置profiles属性, 标签中定义了一个 profile 属性,多个属性值可以使用逗号分隔

<beans profile="dev">
    <bean id="devDatasourceConfig"
      class="org.baeldung.profiles.DevDatasourceConfig" />
</beans>

设置profile

可以通过多种方式设置profile向容器中注册bean。

WebApplicationInitializer 接口

web环境中,可以通过实现WebApplicationInitializer接口配置ServletContext上下文。

@Configuration
public class MyWebApplicationInitializer
  implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter(
          "spring.profiles.active", "dev");
    }
}

ConfigurableEnvironment 接口

通过ConfigurableEnvironment接口直接设置profile

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("someProfile");

Web.xml

web开发者可以在web.xml中使用context param激活profile属性

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
</context-param>

JVM 设置

profiles属性也可以通过JVM系统参数设置,并在应用启动时激活相关属性

-Dspring.profiles.active=dev

系统环境变量

Unix系统中,profiles可以通过声明系统变量来激活

export spring_profiles_active=dev

Maven设置

Spring profiles属性通过maven配置文件声明激活。

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

在编译打包时,通过以下动态参数传递,直接指定profile属性,开发不需要改动任何代码。这种方式在实际开发中经常使用,编译打包完成后,直接交付给运维团队

mvn clean package -Pprod

Profiles In Test

开发测试时,使用@ActiveProfile注解指定需要激活的profile。

@ActiveProfiles("dev")

目前为止,已知多种方式激活profile属性,它们的优先级,从高到低分别为:

  • Context parameter in web.xml
  • WebApplicationInitializer
  • JVM System parameter
  • Environment variable
  • Maven profile

默认Profile

如果没有指定profile,Spring激活默认的profile - default, 可以在属性文件值修改 spring.profiles.default 的值,从而修改默认profile的名字

spring.profiles.default=none

获取生效的Profiles

Spring通过@Profile注解激活/禁止beans, 但是开发者希望获取生效的Profiles列表。有两种方式可以实现:

  • 使用 Environment 对象
  • 获取spring.profiles.active属性值

使用Environment

通过注入Environment bean获取激活的profiles

public class ProfileManager {
    @Autowired
    private Environment environment;
    public void getActiveProfiles() {
        for (String profileName : environment.getActiveProfiles()) {
            System.out.println("Currently active profile - " + profileName);
        }
    }
}

使用spring.profiles.active

此外,可以通过注入spring.profiles.active属性值来获取有效的profiles。

public class ProfileManager {
    //如果配置多个属性,则覆盖get方法 迭代出每一个有效的profile
    @Value("${spring.profiles.active}")
    private String activeProfiles;
    public String getActiveProfiles() {
        for (String profileName : activeProfiles.split(",")) {
            System.out.println("Currently active profile - " + profileName);
        }
    }
}

但是,如果应用中没有profile,上述代码,由于缺少配置将会导致应用启动失败,为了避免这种情况,可以定义个 kong的字符串作为默认值。

//@Value("${spring.profiles.active}")
@Value("${spring.profiles.active:}")
private String activeProfile;

SpringBoot Profiles

Spring Boot 支持以上所有的功能,并增加了一些额外的特性。

设置Profiles

在Spring Boot 默认的配置文件 - application.properties 激活

spring.profiles.active=dev

通过启动类设置profile

//setAdditionalProfiles 不是静态方法,在实际使用中需要注意
SpringApplication.setAdditionalProfiles("dev");

使用spring-boot-maven-plugin插件

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <profiles>
                <profile>dev</profile>
            </profiles>
        </configuration>
    </plugin>
    ...
</plugins>

执行maven命令

mvn spring-boot:run

Profile-specific Properties Files

Spring Boot 核心特性之一是定义了基于profile的配置文件解析规则。配置文件必须以-{profile}.properties格式命名。Spring Boot自动加载解析application.properties文件,并根据profile指定,加载特定的 -{profile}.properties 文件。

例如,需要配置开发/生产两种数据源,名称分别为application-dev.properties、application-production.properties。

application-production.properties使用MYSQL数据源

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root

application-dev.properties 使用内存数据库

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

单文件配置

为了简化不同环境的配置,开发者可以在同一个文件中定义所有属性,并使用分隔符来指定配置文件。

my.prop=used-always-in-all-profiles
#---
spring.config.activate.on-profile=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root
#---
spring.config.activate.on-profile=production
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

Profile Group

Spring Boot 2.4 添加的另一个特性 - Profile Group, 顾明思义,它允许开发者将类似的配置文件分组放置在一起。

假设一个场景:需要为生产环境提供多个配置概要文件,例如,生产环境中的数据库proddb、调度程序的prodquartz。

spring.profiles.group.production=proddb,prodquartz

到此这篇关于Spring Profiles使用方法详解的文章就介绍到这了,更多相关Spring Profiles内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring Boot配置特定属性spring.profiles的方法

    Spring Boot配置特定属性spring.profiles SpringBoot能使用application- {你的自定义profile名称myProfileName} .properties模式添加任何你指定配置文件到其属性文件. 要加载特定的配置文件属性文件,我们可以使用命令行选项-Dspring.profiles.active = myProfileName. 缺省默认SpringBoot是加载application.properties,无需任何-Dspring.profile.

  • 浅谈xml配置spring profiles的几个注意点

    先贴正确配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/

  • 详解Spring Boot Profiles 配置和使用

    介绍 Spring Profiles 提供了一套隔离应用配置的方式,不同的 profiles 提供不同组合的配置,在不同的环境中,应用在启动时通过选择激活某些特定的 profiles 来适应运行时环境,以达到在不同的环境可以使用相同的一套程序代码. 环境 JDK 8 Maven 3 IntelliJ IDEA 2016 Spring Boot 1.5.2.RELEASE @Profiles 你可以在任何 @Component(@Service,@Repository) 或 @Configurat

  • SpringBoot Profiles 多环境配置及切换

    目录 前言 默认环境配置 默认运行环境 多环境配置 多环境切换 小结 前言 大部分情况下,我们开发的产品应用都会根据不同的目的,支持运行在不同的环境(Profile)下,比如: 开发环境(dev) 测试环境(test) 预览环境(pre) 生产环境(prod) 这里的 环境 实际上是一个统称,不同的环境可能代表着 使用的域名.端口.实例数目是不同的: 连接的数据库地址.端口.名称是不同的: 使用的日志输出格式.级别.保存时间是不同的: 以数据库为例,应用在开发环境下运行时,连接的是开发环境对应的

  • SpringBoot激活profiles的几种方式

    多环境是最常见的配置隔离方式之一,可以根据不同的运行环境提供不同的配置信息来应对不同的业务场景,在SpringBoot内支持了多种配置隔离的方式,可以激活单个或者多个配置文件. 激活Profiles的方式 激活的profiles要在项目内创建对应的配置文件,格式为application-{profile}.yml. 命令行方式 命令行方式是一种外部配置的方式,在执行java -jar命令时可以通过--spring.profiles.active=test的方式进行激活指定的profiles列表.

  • spring boot实现profiles动态切换的示例

    具体做法: 1.首先在pom中添加profiles: <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <spring.profiles.active>dev</spring.profiles.active

  • Spring Profiles使用方法详解

    目录 Spring Profiles bean使用profile注解 XML声明profile 设置profile WebApplicationInitializer 接口 ConfigurableEnvironment 接口 Web.xml JVM 设置 系统环境变量 Maven设置 Profiles In Test 默认Profile 获取生效的Profiles 使用Environment 使用spring.profiles.active SpringBoot Profiles 设置Prof

  • Java Spring MVC 上传下载文件配置及controller方法详解

    下载: 1.在spring-mvc中配置(用于100M以下的文件下载) <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!--配置下载返回类型--> <bean class="or

  • Spring MVC框架配置方法详解

    本文实例为大家分享了Spring MVC框架配置方法,供大家参考,具体内容如下 1.概述 Spring MVC 作用:用来实现前端浏览器与后面程序的交互 Spring MVC 是基于Spring 的MVC框架,所谓MVC(model,controller,view) ,整个Spring MVC 作用就是,基于Spring 将model(数据)在controller(后台程序) ,view(前端浏览器)之间交互 至于Spring MVC优点缺点,了解不深 不作评价, 2.引用的jar包 既然是基于

  • Spring Boot项目中定制拦截器的方法详解

    这篇文章主要介绍了Spring Boot项目中定制拦截器的方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Servlet 过滤器属于Servlet API,和Spring关系不大.除了使用过滤器包装web请求,Spring MVC还提供HandlerInterceptor(拦截器)工具.根据文档,HandlerInterceptor的功能跟过滤器类似,但拦截器提供更精细的控制能力:在request被响应之前.request被响应之后.视

  • Spring事务管理原理及方法详解

    这篇文章主要介绍了Spring事务管理原理及方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 事务,在日常开发或者面试中都必定会涉及到.开发工作中,结合数据库开发理解就是:一组dml要么全部成功执行提交,要么因为某一个操作异常,撤销之前所做的成功的操作,整体执行失败.再简单点的一句话:生死与共. 由此,可以看出,事务的必要性:在开发工作中,保证操作数据的安全性.事务的控制也就是保证数据的访问安全性. 一.事务的四大特性 A:原子性(ato

  • Spring Cloud Hystrix异常处理方法详解

    这篇文章主要介绍了Spring Cloud Hystrix异常处理方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在调用服务执行HsytrixCommand实现的run()方法抛出异常时,除HystrixBadRequestException之外,其他异常都会认为是Hystrix命令执行失败并触发服务降级处理逻辑. 异常处理 当Hystrix命令因为异常(除了HystrixBadRequestException异常)进入服务降级逻辑之后

  • Spring Boot读取resources目录文件方法详解

    这篇文章主要介绍了Spring Boot读取resources目录文件方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下,因此,合同协议PDF模板.Excel格式的统计报表等模板的存放位置是resources/template/test.pdf,下面提供两种读取方式,它们分别在windows和Linux

  • Spring data elasticsearch使用方法详解

    这篇文章主要介绍了Spring data elasticsearch使用方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.准备 1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> &l

  • Spring Boot自定义错误视图的方法详解

    Spring Boot缺省错误视图解析器 Web应用在处理请求的过程中发生错误是非常常见的情况,SpringBoot中为我们实现了一个错误视图解析器(DefaultErrorViewResolver).它基于一些常见的约定,尝试根据HTTP错误状态码解析出错误处理视图.它会在目录/error下针对提供的HTTP错误状态码搜索模板或者静态资源,比如,给定了HTTP状态码404,它会尝试搜索如下模板或者静态资源: /<templates>/error/404.<ext> - 这里<

  • IntelliJ IDEA 的 Spring 项目如何查看 @Value 的配置和值(方法详解)

    当你打开项目或者项目中的文件的时候,如果你有 Spring 的 Value 的配置,Intellij 将会自动将参数替换为值. 如果你单击上面的值,那么这个配置参数将会显示为配置的参数名. 如果你还想显示值的话,你需要重新打开这个文件或者项目. 有没有什么快捷键可以快速进行切换. 快捷键 这个配置是在 Intellij 的 Code > Folding 中进行配置的. 快捷键是是 Ctrl + NumberPad + 快捷键是是 Ctrl + NumberPad - NumberPad +,这个

随机推荐