SpringBoot - 读取配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mytt_10566/article/details/81211550

参考文档:https://docs.spring.io/spring-boot/docs/1.5.14.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

1.  读取核心配置文件

例如application.properties或application.yml

application.yml配置文件内容:

user: 
  name: HAHAHA
  age: 18

(1)使用@Value("${key}")注解

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

@Value("${user.age}")
private int age;

(2)使用@ConfigurationProperties注解

该注解在1.5.X时去掉了location属性,需使用@PropertySource指定配置文件路径;由于是主配置文件,所以不需要@PropertySource;

在使用@ConfigurationProperties注解时通过value或prefix属性指定前缀,其余key部分需要和成员变量名一致(支持的写法参考2.1里的说明)

@Component
@ConfigurationProperties(prefix = "user")
// @ConfigurationProperties("user")
// @ConfigurationProperties(value= "user")
public class ApplicationProperties {

    private String name;
    private int age;

    get、set略
}

(3)使用Environment

@Autowired
private Environment env;

System.out.println(env.getProperty("user.name") + " " + env.getProperty("user.age"));
 

2. 读取自定义配置文件

2.1 使用@ConfigurationProperties:指定前缀、@PropertySource:指定自定义配置文件路径

在配置文件中配置了head-pic格式的key,对应java中headPic属性,这样的形式也是可以正确解析的。在官方文档中列出的集中支持的解析格式:

  • user.headPic:标准驼峰语法
  • user.head-pic:虚线表示法,推荐在.properties和.yml文件中使用
  • user.head_pic:下划线表示法,在.properties和.yml文件中使用的可替代格式
  • USER_HEAD_PIC:大写格式,推荐系统变量使用

对于多层级属性的解析如foo.security.username=foo或者数组格式,可以参考官方文档里的说明

(1)config/config.properties

user.headPic=headPic.png
#user.head-pic=headPic.png
#user.head_pic=headPic.png
#USER_HEAD_PIC=headPic.png

user.nickname=mytt_10566

(2)配置类 

@Component
@ConfigurationProperties(prefix = "user")
@PropertySource("classpath:config/config.properties")
public class ConfigProperties {

    private String headPic;
    private String nickname;

    get、get略
}

2.2 @PropertySource:指定自定义配置文件路径,Environment读取属性设置到java类中,同时注册为bean

这种写法来源于@PropertySource源码上的说明,这只是个学习的例子,一般都是用上一种解决方式或者直接使用@Value注解

(1)配置文件同2.1(1)

(2)普通java类

public class ConfigProperties {

    private String headPic;
    private String nickname;

    get、get略
}

(3)配置类

@Configuration
@PropertySource("classpath:config/config.properties")
public class AppConfiguration {
    
    @Autowired
    private Environment env;
    
    @Bean
    public ConfigProperties configProperties() {
        ConfigProperties configProperties = new ConfigProperties();
        configProperties.setHeadPic(env.getProperty("user.headPic"));
        configProperties.setNickname(env.getProperty("user.nickname"));
        return configProperties;
    }
}

猜你喜欢

转载自blog.csdn.net/mytt_10566/article/details/81211550