Spring Boot 外部化配置

1.配置随机值

Spring Boot的配置支持使用随机值,在配置文件中以${random.xxx}形式添加,具体有以下几种类型:

value1=${random.long}
value2=${random.long(value,[max])}
value3=${random.int}
value4=${random.int(value,[max])}
value5=${random.uuid}
value6=${random.value}

2.属性中的占位符

在Spring Boot的配置文件中,可以引用以前定义的值。

app.name=MyApp
app.description=${app.name} is a Spring Boot application

3.多环境配置

Spring Boot中可以指定加载不同环境的环境的配置文件,通过spring.profiles.active属性指定加载不同环境配置文件。

不同环境配置文件使用application-xxx.properties或者application-xxx.yml形式命名即可,这里xxx就是环境值。

Spring Boot多环境配置支持加载多个环境配置,可以通过spring.profiles.active[0]=xxx或者spring.profiles.active=xxx,yyy,zzz形式指定加载相应环境配置。

如果多个环境中出现相同的配置属性,生效属性值的会是最后加载环境的配置中的属性值。

#方式一
spring.profiles.active[0]=default
spring.profiles.active[1]=dev
spring.profiles.active[2]=prod

#方式二
spring.profiles.active=default,dev,prod

4.获取配置文件中属性值

方式一:在Spring管理的Bean中使用@Value("${xxx})获取,这里xxx就是属性的key。

import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

方式二:在Spring管理的Bean中注入org.springframework.core.env.Environment,使用环境类获取配置值。

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class EnvironmentBean implements InitializingBean {
    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
        String appName = environment.getProperty("spring.application.name");
        Integer serverPort = environment.getProperty("server.port", Integer.class);
    }
}

5.多配置的YAML文档

Spring Boot中可以在一个YAML文档指定多个环境的配置信息,通过配置spring.profiles,指示文档配置在何种环境生效。

server:
  address: 192.168.1.100
---
spring:
  profiles: development
server:
  address: 127.0.0.1
---
spring:
  profiles: production,eu-central
server:
  address: 192.168.1.120

6.加载.properties配置文件

使用@PropertySource("classpath:xxx.properties")指定配置文件路径。

可以使用@ConfigurationProperties(prefix = "xxx")指定配置属性前缀,默认前缀为空。

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "my.love")
@PropertySource("classpath:config/simple.properties")
public class SimpleProperties {
    private String song;
    private String food;
    private List<String> color;
}

7.加载.yml配置文件

方式一:在Spring Boot管理的Bean中使用YamlPropertiesFactoryBean把yaml文件注入到系统配置中。

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "my.enjoy")
public class SimpleYaml implements InitializingBean {
    private List<String> website;
    private String openSource;


    /**
     * 使用YamlPropertiesFactoryBean加载yaml配置文件
     *
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("config/simple.yml"));
        propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
        return propertySourcesPlaceholderConfigurer;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(this.toString());
    }
}

方式二:使用YamlMapFactoryBean加载yaml文件为Map,自行读取

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.Map;

@Data
@Component
public class SimpleYaml2 implements InitializingBean {
    private Map<String, Object> object = loadYaml();

    private static Map<String, Object> loadYaml() {
        YamlMapFactoryBean yaml = new YamlMapFactoryBean();
        yaml.setResources(new ClassPathResource("config/simple.yml"));
        return yaml.getObject();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(this.toString());
    }
}

方式三:扩展PropertySourceFactory,使它支持加载yaml文件

扩展PropertySourceFactory,实现一个加载yaml文件的配置文件工厂类

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.List;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

@PropertySource(value="xxx",factory="xxx")中指定工厂为自定义加载yaml文件的配置文件工厂类

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "my.like")
@PropertySource(value = "classpath:config/simple.yml", factory = YamlPropertySourceFactory.class)
public class SimpleYaml3 implements InitializingBean {
    private String food;
    private List<String> pc;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(this.toString());
    }
}

8.为配置文件中的自定义属性增加注释

在IDEA中,经常使用自定义属性时会出现警告,并且没有注释,就像下图:

example

可以在 src/main/resources/META-INF 路径创建additional-spring-configuration-metadata.json属性元文件,为该属性值添加说明:

example

文件内容:

{
  "properties": [
    {
      "name": "alone.properties",
      "type": "java.lang.String",
      "description": "A lonely attribute,We annotate him.",
      "defaultValue": "alone"
    }
  ]
}

查看效果:

example


一些注意事项:

  • 用ide开发时,.properties文件的默认编码为GBK,获取中文值会乱码;而.yml文件的默认编码为UTF-8,则没有中文乱码的问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值