【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()+"\n环境:"+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

可以叠加多个资源文件

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值