第一种@ConfigurationProperties
spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
password: 111111
url: jdbc:mysql://localhost:3306/test
username: root
//取配置文件中spring.datasource.druid下的内容
@ConfigurationProperties(prefix = "spring.datasource.druid")
@Component
public class DatasourcePro {
private String url;
private String username;
private String password;
// 配置文件中是driver-class-name, 横杠会自动转换成驼峰
private String driverClassName;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
}
@RestController
@RequestMapping(value = "/config")
public class ConfigurationPropertiesController {
@Autowired
private DatasourcePro datasourcePro;
@RequestMapping("/getConfig")
public Map<String, Object> test(){
Map<String, Object> map = new HashMap<>();
map.put("url", datasourcePro.getUrl());
map.put("userName", datasourcePro.getUsername());
map.put("password", datasourcePro.getPassword());
map.put("className", datasourcePro.getDriverClassName());
return map;
}
}
第二种@Value
spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
@Component
public class DatasourcePro {
@Value("${spring.datasource.druid.driver-class-name}")
private String driverClassName;
}
总结
@ConfigurationProperties支持批量注入配置文件中的属性,如果配置文件中值多的话,可以专门编写一个JavaBean来进行映射。如果只有单个值的话,就可以使用@Value。