Springboot读取配置文件的方法
【注】 项目中的全部使用到的配置文件(application.properties、其他properties文件)中的属性key名称不能重复,因为项目启动后都会将这些配置文件放入到Environment环境中。如果属性key重复,会出现属性值覆盖的情况。
1、@Value注解
直接代码进行演示。
application.properties类配置如下:
server.port=8080
server.servlet.context-path=/
配置文件类:
@Data
@Component
public class ValueConfig {
@Value("${server.port}")
private String port;
}
2、@ConfigurationProperties注解方式
SpringBoot 提供该注解将配置文件的值映射到类上使用。
【注】 使用@ConfigurationProperties配置类必须有set方法,否则无法注入属性值。
lakala.properties类配置如下:
lakala.appId=lakala
lakala.lakala_appId=lakala_appId
配置文件类:
@Data
@Component
@ConfigurationProperties(prefix = "lakala")
public class LakalaConfig {
private String appId;
private String lakala_appId;
}
3、@PropertySource+@Value
Spring框架提供了PropertySource注解,目的是加载指定的属性文件。
【注】 @PropertySource注解可以放到项目任何位置,不一定放置在配置类上,也可以放置在SpringBoot的启动类上,他的主要作用是将外部的配置文件加载到Environment中。
wechat.properties类配置如下:
wechat.appId=wechat
wechat.wechat_appId=wechat_appId
配置类代码如下:
@Component
@PropertySource(value = {"classpath:config/wechat.properties"})
public class WechatConfig {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.wechat_appId}")
private String lakala_appId;
}
4、@ConfigurationProperties+@PropertySource+@Value
【注】 不建议使用,使用了@PropertySource+@ConfigurationProperties可以不使用@Value。
wechat.properties类配置如下:
wechat.appId=wechat
wechat.wechat_appId=wechat_appId
配置类代码如下:
@Component
@ConfigurationProperties("wechat")
@PropertySource(value = {"classpath:config/wechat.properties"})
public class WechatConfig {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.wechat_appId}")
private String lakala_appId;
}
5、@ConfigurationProperties+@Value
【注】 这种方式无法读取其他外部配置文件,如果要读取其他配置文件,需要使用@PropertySource注解。(使用场景较少)
application.properties类配置如下:
wechat.appId=wechat
wechat.wechat_appId=wechat_appId
配置类代码如下:
@Component
@ConfigurationProperties("wechat")
public class WechatConfig {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.wechat_appId}")
private String lakala_appId;
}
6、Environment类
【注】 只有将配置文件加载到环境变量里面才能读取到,application.properties默认加载到环境变量,外部配置文件需要借助于@PropertySource注解
@Autowired
private Environment environment;
// 通过此方法获取属性值
environment.getProperty("wechat.wechat_appId");