开发过程中,引入自定义配置是很常见的,主要记录两种:
1、@Value() 注解
2、@ConfigurationPropertie()注解
一、配置文件引入问题
springboot支持两种配置文件:*.properties 和 *.yml
首先先提一下,在springboot 1.5版本以后是通过@PropertySource(“path”)无法加载YAML文件,官方也给出说明
24.7.4 YAML Shortcomings
YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.
如果想引入yml文件,有两种方式:
① 将自定义配置放在application-*.yml中,
② 通过PropertySourcePlaceholderConfigurer来加载yml文件
上代码
// 加载YML格式自定义配置文件
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new FileSystemResource("config.yml"));//File引入
// yaml.setResources(new ClassPathResource("youryml.yml"));//class引入
configurer.setProperties(yaml.getObject());
return configurer;
}
二、自定义配置
本篇以*.properties为例
1、@Value() 注解
引入配置文件
/**
* 程序入口
* @author guocheng.L
*/
@SpringBootApplication
// 加载配置文件
@PropertySource("classpath:config2.properties")
public class MyspringbootApplication {
public static void main(String[] args) {
SpringApplication.run(MyspringbootApplication.class, args);
}