有两种方式,一种是通过@PropertySource
注解,然后使用@Value
逐个注入配置。
@Configuration
@PropertySource("classpath:test.properties")
public class ELConfig {
@Value("${book.name}")
private String bookName;
//注意!配置一个PropertySourcesPlaceholderConfigurer的Bean
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
return new PropertySourcesPlaceholderConfigurer();
}
public void outputSource() {
System.out.println(bookName);
}
}
另外一种方式是通过@ConfigurationProperties
注解,通过getter、setter方法注入及获取配置。
properties配置
author.name=listen
author.age=26
@Component
//可以使用locations指定读取的properties文件路径,如果不指定locations就会读取默认的properties配置文件
@ConfigurationProperties(prefix = "author")
public class AuthorSettings {
private String name;
private Long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
最后一种
URL url = ResourceUtils.getURL("classpath:xx_private_key.pem");