zoukankan      html  css  js  c++  java
  • springBoot 多环境配置问题

    转载:

    http://412887952-qq-com.iteye.com/blog/2307104

    多环境配置

           以上都不是重点,这才是重点,这才是重点,这才是重点,重要的事情说3遍。我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

           对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。

           在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

       application-dev.properties:开发环境

       application-test.properties:测试环境

       application-prod.properties:生产环境

           至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

    如:spring.profiles.active=test就会加载application-test.properties配置文件内容

    多环境高级应用

         在某些情况下,应用的某些业务逻辑可能需要有不同的实现。例如邮件服务,假设EmailService中包含的send(String email)方法向指定地址发送电子邮件,但是我们仅仅希望在生产环境中才执行真正发送邮件的代码,而开发环境里则不发送以免向用户发送无意义的垃圾邮件。

           我们可以借助Spring的注解@Profile实现这样的功能,这样需要定义两个实现EmailService借口的类:

    /**

     * 发送邮件接口.

     * @author Angel(QQ:412887952)

     * @version v.0.1

     */

    public interface EmailService {

        /**发送邮件*/

        publicvoid send();

    }

    发送邮件的具体实现(dev-开发环境的代码):

    @Service

    @Profile("dev") //开发环境的时候.

    public class DevEmailServiceImpl implements EmailService{

        @Override

        publicvoid send() {

           System.out.println("DevEmailServiceImpl.send().开发环境不执行邮件的发送.");

        }

    }

    发送邮件的具体实现(prod-生产环境的代码):

    @Service

    @Profile("prod") //生产环境.

    public class ProdEmailServiceImpl2 implements EmailService{

       

        @Override

        publicvoid send() {

           System.out.println("DevEmailServiceImpl.send().生产环境执行邮件的发送.");

           //具体的邮件发送代码.

           //mail.send();

        }

    }

    @Profile("dev")表明只有Spring定义的Profile为dev时才会实例化DevEmailService这个类。那么如何设置Profile呢?

    在配置文件中指定

    application.properties中加入:

    spring.profiles.active=dev
  • 相关阅读:
    Compression algorithm (deflate)
    tcpip数据包编码解析(chunk and gzip)_space of Jialy_百度空间
    What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
    gzip压缩算法: gzip 所使用压缩算法的基本原理
    Decompressing a GZip Stream with Zlib
    Frequently Asked Questions about zlib
    how to decompress gzip stream with zlib
    自己动手写web服务器四(web服务器是如何通过压缩数据,web服务器的gzip模块的实现)
    What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
    C语言抓http gzip包并解压 失败 C/C++ ChinaUnix.net
  • 原文地址:https://www.cnblogs.com/tuyf/p/7373392.html
Copyright © 2011-2022 走看看