`
1028826685
  • 浏览: 943510 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类

Spring Boot Profile使用

 
阅读更多

Spring Boot使用@Profile注解可以实现不同环境下配置参数的切换,任何@Component@Configuration注解的类都可以使用@Profile注解。

例如:

@Configuration
@Profile("production")
public class ProductionConfiguration {
    // ...
}

 通常,一个项目中可能会有多个profile场景,例如下面为test场景:

@Configuration
@Profile("test")
public class TestConfiguration {
    // ...
}

 在存在多个profile情况下,你可以使用spring.profiles.active来设置哪些profile被激活。spring.profiles.include属性用来设置无条件的激活哪些profile。

例如,你可以在application.properties中设置:

或者在application.yaml中设置:

spring.profiles.active属性可以通过命令行参数或者资源文件来设置,其查找顺序,请参考Spring Boot特性

自定义Profile注解

@Profile注解需要接受一个字符串,作为场景名。这样每个地方都需要记住这个字符串。Spring的@Profile注解支持定义在其他注解之上,以创建自定义场景注解。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface Dev {
}

 这样就创建了一个@Dev注解,该注解可以标识bean使用于@Dev这个场景。后续就不再需要使用@Profile("dev")的方式。这样即可以简化代码,同时可以利用IDE的自动补全:)

多个Profile例子

下面是一个例子:

package com.javachen.example.service;
 
public interface MessageService {
  String getMessage();
}

 对于MessageService接口,我们可以有生产和测试两种实现:

package com.javachen.example.service;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
 
@Component
@Profile({ "dev" })
public class HelloWorldService implements MessageService{
 
  @Value("${name:World}")
  private String name;
 
  public String getMessage() {
    return "Hello " + this.name;
  }
 
}

 

package com.javachen.example.service;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
 
@Component
@Profile({ "prod" })
public class GenericService implements MessageService {
 
  @Value("${hello:Hello}")
  private String hello;
 
  @Value("${name:World}")
  private String name;
 
  @Override
  public String getMessage() {
    return this.hello + " " + this.name;
  }
 
}

 Application类为:

@SpringBootApplication
public class Application implements CommandLineRunner {
  private static final Logger logger = LoggerFactory.getLogger(Application.class);
 
  @Autowired
  private MessageService messageService;
 
  @Override
  public void run(String... args) {
    logger.info(this.messageService.getMessage());
    if (args.length > 0 && args[0].equals("exitcode")) {
      throw new ExitException();
    }
  }
 
  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }
}

 实际使用中,使用哪个profile由spring.profiles.active控制,你在resources/application.properties中定义spring.profiles.active=XXX,或者通过-Dspring.profiles.active=XXXXXX可以是dev或者prod或者dev,prod需要注意的是:本例中是将@Profile用在Service类上,一个Service接口不能同时存在超过两个实现类,故本例中不能同时使用dev和prod。

通过不同的profile,可以有对应的资源文件application-{profile}.properties。例如,application-dev.properties内容如下:

name=JavaChen-dev

 application-prod.properties内容如下:

接下来进行测试。spring.profiles.active=dev时,运行Application类,查看日志输出。

2016-02-22 15:45:18,470 [main] INFO  com.javachen.example.Application - Hello JavaChen-dev

spring.profiles.active=prod时,运行Application类,查看日志输出。

2016-02-22 15:47:21,270 [main] INFO  com.javachen.example.Application - Hello JavaChen-prod

logback配置多Profile

在resources目录下添加logback-spring.xml,并分别对dev和prod进行配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
 
    <springProfile name="dev">
        <logger name="com.javachen.example" level="TRACE" />
        <appender name="LOGFILE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            </encoder>
        </appender>
    </springProfile>
 
    <springProfile name="prod">
        <appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>log/server.log</File>
            <rollingPolicy
                    class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <FileNamePattern>log/server_%d{yyyy-MM-dd}.log.zip</FileNamePattern>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
            </layout>
        </appender>
    </springProfile>
 
    <root level="info">
        <appender-ref ref="LOGFILE" />
    </root>
 
    <logger name="com.javachen.example" level="DEBUG" />
</configuration>

 这样,就可以做到不同profile场景下的日志输出不一样。

maven中的场景配置

使用maven的resource filter可以实现多场景切换。

<profiles>
    <profile>
        <id>prod</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build.profile.id>prod</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <build.profile.id>dev</build.profile.id>
        </properties>
    </profile>
</profiles>
 
<build>
        <filters>
            <filter>application-${build.profile.id}.properties</filter>
        </filters>
 
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
</build> 

 这样在maven编译时,可以通过-P参数指定maven profile即可。

总结

使用Spring Boot的Profile注解可以实现多场景下的配置切换,方便开发中进行测试和部署生产环境。

本文中相关代码在github上面。

分享到:
评论

相关推荐

    Spring-Boot-Reference-Guide, Spring Boot Reference Guide中文翻译 -《Spring Boot参考指南》.zip

    综上,《Spring Boot参考指南》覆盖了Spring Boot的各个方面,无论是初学者还是经验丰富的开发者,都能从中受益匪浅,快速掌握Spring Boot的使用技巧和最佳实践。这份中文翻译版本的出现,无疑为国内的Spring Boot...

    Spring Boot教程.pdf

    在 Profile 模式中,我们可以使用 @Profile 注解来标注配置类,并使用 spring.profiles.active 属性来激活当前的 Profile。同时,我们也可以使用 @ConditionalOnProfile 注解来标注条件性配置。 四、日志处理 日志...

    spring boot 例子代码

    此外,Spring Boot 支持使用 Profile 功能,可以根据不同的运行环境加载不同的配置。 最后,测试也是 Spring Boot 的强项之一。它提供了 `SpringBootTest` 和 `WebMvcTest` 等注解,方便编写集成测试和控制器测试,...

    Spring Boot技术培训

    - **简化配置**:在没有使用 Spring Boot 时,构建项目通常需要大量的 XML 配置文件,这不仅使得项目结构变得复杂,而且在配置过程中容易出错。 - **减少依赖冲突**:整合第三方框架时往往需要手动配置 JAR 包,这会...

    Spring boot中文教程(Spring Boot Reference Guide 1.3.0.BUILD)

    为了更好地适应不同的部署环境,Spring Boot提供了多种配置特性,包括外化配置、配置随机值、访问命令行属性、使用YAML代替Properties文件、特定的Profile属性、属性占位符等。YAML是一种标记语言,它易于阅读,适用...

    Spring Boot入门与实战_springboot_spring_

    2. **Profile切换**:通过`spring.profiles.active`属性,可以在不同环境下切换配置。 3. **外部化配置**:允许将配置存储在单独的文件或环境变量中,提高灵活性。 **五、Spring Boot 集成Spring MVC** 1. **配置...

    Spring Boot参考指南.pdf

    - **使用Spring Boot Maven插件**:指导如何使用Spring Boot的Maven插件进行构建。 - **Gradle**:讲解如何使用Gradle构建工具。 - **Ant**:虽然较少提及,但也支持使用Ant进行构建。 - **Starters**:介绍...

    Spring Boot 中文文档 参考手册.pdf

    应用的配置通常放在`application.properties`或`application.yml`文件中,Spring Boot支持Profile特定的配置,如`application-dev.properties`用于开发环境,`application-prod.properties`用于生产环境。...

    spring-boot中文参考指南

    - **使用Spring Boot**:介绍Spring Boot的基本概念、特性及其应用场景。 - **了解Spring Boot特性**:包括Spring Boot如何自动配置、集成外部系统等。 - **迁移到生产环境**:讨论如何将开发中的应用部署到生产环境...

    Spring boot视频

    - **Kotlin 支持**:Spring Boot 2.0 开始正式支持 Kotlin,允许开发者使用 Kotlin 编写 Spring Boot 应用。 - **Spring Data JDBC**:Spring Data JDBC 是一个新的模块,提供了一种轻量级的数据访问层,替代了传统...

    ### Spring Boot 框架介绍与使用技巧

    - **使用外部配置文件**:Spring Boot 支持使用外部配置文件,如 `application-{profile}.properties`,可以在不同的环境中加载不同的配置。这种方式非常适合于多环境部署的应用程序。 ##### 2.8 使用 Spring Boot ...

    spring boot指导手册

    首先,介绍部分为读者提供了文档的基本结构和获取帮助的途径,以及使用Spring Boot的初步步骤,包括系统要求、安装指南和如何开始开发第一个Spring Boot应用。系统要求部分讨论了Servlet容器的配置,而安装指南则...

    Spring Boot 常用注解.rar

    **Spring Boot 常用注解详解** Spring Boot以其简洁的配置、快速的启动和集成众多优秀框架的能力,成为Java开发领域中的热门选择。在Spring Boot应用中,注解起着至关重要的作用,它们简化了配置,使得代码更加简洁...

    Spring Boot基础1

    Spring Boot 的应用程序可以通过 Maven 打包成一个可执行的 jar 包,开发者可以使用 java -jar 命令来执行该应用程序。这使得应用程序的部署变得非常方便。 Spring Boot 是一个功能强大且灵活的框架,它可以帮助...

    Spring Boot 参考指南

    - **属性值**:Spring Boot 允许使用外部配置文件来存储应用配置信息。 - **访问配置信息**:可以通过多种方式访问这些配置信息。 - **Application Properties**:Spring Boot 支持将配置文件中的属性映射到 Java...

    基于Spring Boot框架的全面学习项目.zip

    2. 配置管理学习如何编写配置文件(如application.properties或application.yml),管理应用的各种属性,并利用Spring Boot的Profile功能实现不同环境下的配置切换。 3. 静态资源与模板引擎整合演示如何整合静态资源...

    Spring Boot多模块配置文件读取

    本文将详细探讨如何在Spring Boot的多模块项目中管理和使用不同的配置文件,以实现低耦合的设计。 首先,了解Spring Boot的默认配置机制。Spring Boot的核心理念是简化配置,它通过`application.properties`或`...

    Spring boot 中文.pdf

    - **使用 Spring Boot**:本节主要介绍 Spring Boot 的核心概念和功能,以及如何利用这些功能来简化开发过程。 #### 二、Spring Boot 入门指南 - **Spring Boot 简介**:Spring Boot 是一种基于 Spring Framework ...

    Spring Boot学习笔记

    - **Spring Boot 1.5.9.RELEASE**:本项目中使用的是 Spring Boot 1.5.9.RELEASE 版本。 **环境配置** 1. **Maven 设置**:需要在 Maven 的 settings.xml 文件中添加配置以确保使用正确的 JDK 版本。 ```xml ...

Global site tag (gtag.js) - Google Analytics