关于springboot读取配置类的几种方法

SpringBoot读取配置的几种方式

读取application文件

在application.yml或者properties文件中添加:

info.address=USA
info.company=Spring
info.degree=high

  • 使用@Value注解读取方式
@Value("info.address")
private String address;
@Value("info.company")
private String company;
@Value("info.degree")
private String degree;
  • 使用@ConfigurationProperties注解读取方式
@Component
@ConfigurationProperties(prefix ="info")
public class InfoConfig2 {

	private String address;
	private String company;
	private String degree;
}

读取指定文件

资源目录下建立config/db-config.properties:

db.username=root

db.password=123456

  • 使用@PropertySource+@Value注解读取方式
@Component
@PropertySource(value ={"config/db-config.properties" })
public class InfoConfig3 {
	@Value("db.username")
	private String username;
	@Value("db.password")
	private String password;
}


注意:@PropertySource不支持yml文件读取。

  • 使用@PropertySource+@ConfigurationProperties注解读取方式
@Component
@ConfigurationProperties(prefix ="db")
@PropertySource(value ={"config/db-config.properties" })
public class InfoConfig3 {
	private String username;
	private String password;
}


  • 使用Environment读取方式

以上所有加载出来的配置都可以通过Environment注入获取到。

@Autowired
private Environment env;
//获取参数
String getProperty(String key);

版权声明:本文为HQqHQhqqhq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。