Spring中读取配置文件的五种方式
作者:A杨宽A
在使用spring或springboot项目开发中,难免会涉及到读取配置文件的各种配置参数的情况,因为当项目的规模上去之后,在单个配置文件中维护所有的配置信息很难满足实际的需要,所以本文给大家介绍了Spring读取配置文件多种方式,需要的朋友可以参考下
Spring中读取配置文件的五种方式
- @Value:只能读取单个配置项
 - @ConfigurationProperties:可以一次性读取多个配置项,将多个配置项转换为Bean对象。需要配合prefix使用。
 - @PropertySource+@Value:获取自定义配置文件的单个配置项。
 - @PropertySource+@ConfigurationProperties:获取自定义配置文件的多个配置项。
 - Environment的getProperty方法获取,很少使用。
 
举例说明:
第一种:@Value注解方式获取
application.yml
server: port: 9201
取值方式:
    @Value("${server.port}")
    private String port;
第二种:@ConfigurationProperties注解方式获取
application.yml
student: name: 张三 age: 18
取值方式:
@Configuration
@ConfigurationProperties(prefix = "student")
public class CaptchaProperties{
	private String name;
	private Integer age;
	...
}
注:需要配和@Component使用,本文中使用的@Configuration,我们查看Configuration注解会发现它使用了@Component注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
...
}
第三种:@PropertyResource + @Value注解方式获取,可读取自定义配置文件。只支持读取.properties类型的配置文件,yml类型的配置文件需要自定义。
student.properties
student.name = 张三 student.age = 18
取值方式:
@Component
@PropertyResouce(value = "classpath:student.properties")
public class Student implements Serializable{
	@Value("${student.name}")
	private String name;
	
	@Value("${student.age}")
	private Integer age;
	...
}
第四种:@PropertyResource + @ConfigurationProperties注解方式获取,可读取自定义配置文件。只支持读取.properties类型的配置文件,yml类型的配置文件需要自定义。
student.properties
student.name = 张三 student.age = 18
取值方式:
/**
 * @Component标识为是Spring的一个组件,只有容器组件,容器才会为ConfigurationProperties提供此注入共    	
 * 功能
 */
@Component
@PropertyResouce(value = "classpath:student.properties")
@ConfigurationProperties(prefix = "student")
public class Student implements Serializable{
	private String name;
	private Integer age;
	...
}
第五种:Environment方式读取,基本很少使用
application.yml
student: name: 张三 age: 18
取值方式:
...
@Autowired
private Environment env;
public String getUserName(){
	return env.getProperty("student.name");
}
...
以上就是Spring中读取配置文件的五种方式的详细内容,更多关于Spring读取配置文件的资料请关注脚本之家其它相关文章!
