zoukankan      html  css  js  c++  java
  • 【spring boot】4.spring boot配置多环境资源文件

    一个spring boot 项目在开发环境、测试环境、生产环境下,好多的配置都是不尽相同的。所以配置多分的资源文件,仅仅在部署在不同环境的时候,选择激活不同的资源文件就可以实现多环境的部署。

    项目结构如下:

    1.配置多个环境下的不同的资源文件

    多个资源文件的格式如下:

    application-{profile}.properties

    {profile}自定义的不同环境标识,本项目中分别对应如下:

    ==========================================================================

     列出各个环境下的资源文件内容:

    application-dev.properties  开发资源文件

    application-pro.properties  生产资源文件

    application-test.properties     测试资源文件

    2.主资源文件中 选择激活一种环境下的资源文件

    spring.profiles.active=dev

     dev就是上面一种资源文件的自定义标识

    3.绑定到一个bean,提供给程序中使用

    package com.sxd.beans;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "com.sxd")
    public class ConfigBean {
    
        private String ip;
        private String value;
    
        public String getIp() {
            return ip;
        }
    
        public void setIp(String ip) {
            this.ip = ip;
        }
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    }
    View Code

    4.程序主入口,激活绑定的bean,顺便使用了

    package com.sxd.firstdemo;
    
    import com.sxd.beans.ConfigBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @SpringBootApplication
    @EnableConfigurationProperties({ConfigBean.class})
    public class FirstdemoApplication {
    
        @Autowired
        ConfigBean configBean;
    
        @RequestMapping("/")
        public String index(){
    
            return "IP:"+configBean.getIp()+"
    环境:"+configBean.getValue();
        }
        public static void main(String[] args) {
            SpringApplication.run(FirstdemoApplication.class, args);
        }
    }
    View Code

    5.启动并访问  ,当前激活的是开发环境资源文件

    ==================================================================================================================

    spring.profiles.active=dev

    是选择一种资源文件

    spring.profiles.include=dev,test,pro

    可以叠加多个资源文件

  • 相关阅读:
    sys模块
    反射
    动态导入模块
    类的静态属性
    多态
    继承
    组合
    linux系统各个子目录的内容
    mysql安装
    Docker 数据卷操作
  • 原文地址:https://www.cnblogs.com/sxdcgaq8080/p/7655114.html
Copyright © 2011-2022 走看看