Springboot(七)多环境配置1 spring.profiles

前言:

    首先系统在不同的环境中,可能需要不同的配置,比如:生产环境、开发环境、测试环境、压测环境等,每个环境数据库访问地址、mq监听地址、文件服务器地址等可能都不一样,那么怎么实现多环境切换,这就是spring.profiles


代码:

首先搭建一个springboot工程

application.yml

spring:
  profiles:
#  可以写多个
    active: prod
  #  include: prod,dev

---
spring:
  profiles: dev
server:
  port: 8081

---
spring:
  profiles: prod
server:
  port: 8082

上面用---把配置分成的三块。第一块:通用的配置     第二块:dev环境的配置  第三块 prod环境的配置,在spring.profiles.active中指定激活下面的哪个配置,spring.profiles:dev 代表这一块配置的名称 dev ,spring.profiles: prod代表这一块配置名称prod.


用prod的配置启动,可以看到端口号为8082


也可以加一个配置类测试,输出端口号:

package com.xhx.springboot.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import sun.tools.jar.CommandLine;

/**
 * made by xuhaixing
 * 18-4-8 下午10:46
 */
@Configuration
public class testProfile {

    @Value("${server.port}")
    private String port;


    @Profile("!dev") //可以用取反操作符,也可以用多个参数
    @Bean
    public CommandLine testPort() {
        System.out.println("--------------" + port);
        return new CommandLine();
    }
}

@Profile注解,可以根据配置文件中指定的环境,监测要执行哪些代码。



我的git代码

猜你喜欢

转载自blog.csdn.net/u012326462/article/details/80687445
今日推荐