spring-boot之(4) profile annotation

  前面说了基于yml文件的不同环境环境配置,spring boot的官方文档里面也给出了对应的注解@Profile,@Profile可以配合@Component和@Configuration使用来实现不同环境配置生效。请看下面代码

  • 不同环境不同配置代码如下

  测试环境代码默认从yml配置文件中获取

 

@Component
@ConfigurationProperties(prefix = "my")
@Profile("test")
public class Config {
    private List<String> servers = new ArrayList<String>();

    public List<String> getServers(){
        return servers;
    }

    public void setServers(List<String> servers){
        this.servers = servers;
    }
}

  而yml配置如下

# common configuration
server:
  port: 80

# 设置生效的配置
spring:
  profiles:
    active: prod

# 日志等级
logging:
  level:
    root: error

test:
  username: test

my:
  servers:
    - test.dev.bar.com
    - test.foo.bar.com

  开发环境的配置代码如下

@Configuration
@Profile("prod")
public class DevConfig extends Config{

    @Override
    public List<String> getServers() {
        List<String> list = new LinkedList<String>();
        list.add("hahaha");
        return list;
    }
}
  • 最后访问http://localhost
test, hello world !!![hahaha]

 

参考资料:

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-configuration-classes

posted @ 2017-04-28 13:28  風之殤  阅读(134)  评论(0)    收藏  举报