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

 更新时间:2020年10月12日 10:56:17   作者:hythzx  
Spring Boot支持在不同的环境下使用不同的配置文件,该技术非常有利于持续集成,在构建项目的时候只需要使用不同的构建命令就可以生成不同运行环境下war包,而不需要手动切换配置文件。

具体做法:

1、首先在pom中添加profiles:

<profiles>
  <profile>
   <id>dev</id>
   <activation>
     <activeByDefault>true</activeByDefault>
   </activation>
   <properties>
     <spring.profiles.active>dev</spring.profiles.active>
   </properties>
   <dependencies>
     <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
     </dependency>
     <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
     </dependency>
   </dependencies>
  </profile>
 
  <profile>
   <id>prod</id>
   <dependencies>
     <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-undertow</artifactId>
     </dependency>
   </dependencies>
   <properties>
     <spring.profiles.active>prod</spring.profiles.active>
   </properties>
  </profile>
</profiles>

dev指开发模式,prod指生产模式,如需其他模式,只需要添加profile即可.

2、在pom.xml的build中添加plugin:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <version>${maven-resources-plugin.version}</version>
  <executions>
   <execution>
     <id>default-resources</id>
     <phase>validate</phase>
     <goals>
      <goal>copy-resources</goal>
     </goals>
     <configuration>
      <outputDirectory>target/classes</outputDirectory>
      <useDefaultDelimiters>false</useDefaultDelimiters>
      <delimiters>
        <delimiter>#</delimiter>
      </delimiters>
      <resources>
        <resource>
         <directory>src/main/resources/</directory>
         <filtering>true</filtering>
         <includes>
           <include>**/*.xml</include>
           <include>**/*.yml</include>
         </includes>
        </resource>
        <resource>
         <directory>src/main/resources/</directory>
         <filtering>false</filtering>
         <excludes>
           <exclude>**/*.xml</exclude>
           <exclude>**/*.yml</exclude>
         </excludes>
        </resource>
      </resources>
     </configuration>
   </execution>
  </executions>
</plugin>

该配置用来在打包的时候修改配置文件。

3、编写DefaultProfileUtil工具类来添加默认启动配置文件:

import org.springframework.boot.SpringApplication;
import org.springframework.core.env.Environment;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * Utility class to load a Spring profile to be used as default
 * when there is no <code>spring.profiles.active</code> set in the environment or as command line argument.
 * If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default.
 */
public final class DefaultProfileUtil {
 
  private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
 
  private DefaultProfileUtil(){
  }
 
  /**
   * Set a default to use when no profile is configured.
   *
   * @param app the spring application
   */
  public static void addDefaultProfile(SpringApplication app) {
    Map<String, Object> defProperties = new HashMap<>();
    /*
    * The default profile to use when no other profiles are defined
    * This cannot be set in the <code>application.yml</code> file.
    * See https://github.com/spring-projects/spring-boot/issues/1219
    */
    defProperties.put(SPRING_PROFILE_DEFAULT, Constants.SPRING_PROFILE_DEVELOPMENT);
    app.setDefaultProperties(defProperties);
    System.out.println(app);
  }
 
  /**
   * Get the profiles that are applied else get default profiles.
   */
  public static String[] getActiveProfiles(Environment env) {
    String[] profiles = env.getActiveProfiles();
    if (profiles.length == 0) {
      return env.getDefaultProfiles();
    }
    return profiles;
  }
}
public class Constants {
 
  public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
  public static final String SPRING_PROFILE_PRODUCTION = "prod";
  private Constants() {
  }
}

4、修改application.yml配置文件,添加(采用application.properties文件):

spring:
  profiles:
   active: #spring.profiles.active#

maven的构建的时候会替换#spring.profiles.active#

5、修改项目的启动类:

@SpringBootApplication
public class Demo1Application {
 
  private static final Logger log = LoggerFactory.getLogger(Demo1Application.class);
 
  public static void main(String[] args) {
   SpringApplication app = new SpringApplication(Demo1Application.class);
   DefaultProfileUtil.addDefaultProfile(app);
   Environment env = app.run(args).getEnvironment();
   log.info("\n----------------------------------------------------------\n\t" +
         "Application '{}' is running! Access URLs:\n\t" +
         "Local: \t\thttp://localhost:{}\n\t" +
         "----------------------------------------------------------",
      env.getProperty("spring.application.name"),
      env.getProperty("server.port"));
  }
}

以上修改完成之后,在启动的时候会显示:The following profiles are active: dev 默认dev模式切换成功。

6、构建项目:

采用mvn clean package -Pprod命令构建,最后的配置文件会被改成:

以上就是spring boot实现profiles动态切换的示例的详细内容,更多关于spring boot实现profiles动态切换的资料请关注脚本之家其它相关文章!

相关文章

  • 一文搞懂Java的SPI机制(推荐)

    一文搞懂Java的SPI机制(推荐)

    Java定义了一套JDBC的接口,但并未提供具体实现类,而是在不同云厂商提供的数据库实现包。这篇文章给大家介绍Java的SPI机制,感兴趣的朋友一起看看吧
    2021-11-11
  • Spring Boot 集成Redisson实现分布式锁详细案例

    Spring Boot 集成Redisson实现分布式锁详细案例

    这篇文章主要介绍了Spring Boot 集成Redisson实现分布式锁详细案例,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-08-08
  • Java泛型 <T> T、 T、<T>的用法小结

    Java泛型 <T> T、 T、<T>的用法小结

    T在Java泛型中,被称作类型变量, 有的方法返回值是<T> T,有的是T,区别在哪里,本文主要介绍了Java泛型 <T> T、 T、<T>的用法小结,具有一定的参考价值,感兴趣的可以了解下
    2023-12-12
  • SpringBoot 嵌入式web容器的启动原理详解

    SpringBoot 嵌入式web容器的启动原理详解

    这篇文章主要介绍了SpringBoot 嵌入式web容器的启动原理详解,具有很好的参考价值,希望对大家有所帮助。
    2021-11-11
  • Java实现简易画图板

    Java实现简易画图板

    这篇文章主要为大家详细介绍了Java实现简易画图板,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • IDEA在plugins里搜不到mybatisx插件的解决方法

    IDEA在plugins里搜不到mybatisx插件的解决方法

    本文主要介绍了IDEA在plugins里搜不到mybatisx插件的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • spring-boot-maven-plugin 配置有啥用

    spring-boot-maven-plugin 配置有啥用

    这篇文章主要介绍了spring-boot-maven-plugin 配置是干啥的,这个是SpringBoot的Maven插件,主要用来打包的,通常打包成jar或者war文件,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • Java经典面试题汇总:网络编程

    Java经典面试题汇总:网络编程

    本篇总结的是Java 网络编程相关的面试题,后续会持续更新,希望我的分享可以帮助到正在备战面试的实习生或者已经工作的同行,如果发现错误还望大家多多包涵,不吝赐教,谢谢
    2021-07-07
  • 通过java.util.TreeMap源码加强红黑树的理解

    通过java.util.TreeMap源码加强红黑树的理解

    通过分析java.util.TreeMap源码来对经典问题红黑树加强理解和理清思路。
    2017-11-11
  • Spring扩展点之BeanFactoryPostProcessor详解

    Spring扩展点之BeanFactoryPostProcessor详解

    这篇文章主要介绍了Spring扩展点之BeanFactoryPostProcessor详解,Spring的设计非常优雅,有很多的扩展点供我们对项目进行扩展,今天学习一下Spring其中扩展点之一的BeanFactoryPostProcessor,需要的朋友可以参考下
    2023-11-11

最新评论