Spring Boot可使用注解的方式将自定义的properties文件映射到实体bean中,比如config.properties文件
config.name=configname
config.password=configpassword
建对应的bean
@Configuration
@ConfigurationProperties(prefix = "config")
@PropertySource("classpath:/config.properties")
public class Config {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
然后只需要在Spring Boot的启动类上面加注解
@EnableConfigurationProperties({Config.class})
使用的时候直接注入即可
@Autowired
Config config;
相关依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>