问题:ConfigurationProperties如何进行对象的赋值,
例, JdbcProperties中有 View对象,如何初始化View中的 prefix,suffix
ConfigurationProperties 的 Relaxed binding:松散绑定
不严格要求属性文件中的属性名与成员变量名一致。支持驼峰,中划线,下划线等等转换,甚至支持对象引导。比如:user.friend.name:代表的是user对象中的friend属性中的name属性,显然friend也是对象。
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
private String driverClassName;
private String url;
private String username;
private String password;
//配置文件以 jdbc.view 开头
private final View view = new View();
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = 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 View getView(){
return this.view;
}
public static class View {
/**
* Spring MVC view prefix.
*/
private String prefix;
/**
* Spring MVC view suffix.
*/
private String suffix;
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
}
application.properties
如果想要初始化View中的 prefix和suffix,则前缀应该为 jdbc.view
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?characterEncoding=utf-8
jdbc.username=ldmiao
jdbc.password=ldm1991
jdbc.view.prefix = qianzhui
jdbc.view.suffix = houzhui
测试:
在Controller中 使用@EnableConfigurationProperties(JdbcProperties.class)引入配置类
通过构造方法注入 JdbcProperties
@RequestMapping("springboot")
@Controller
@EnableConfigurationProperties(JdbcProperties.class)
public class HelloController {
public HelloController(JdbcProperties jdbcProperties){
System.out.println(jdbcProperties.getView().getPrefix());
}
@Autowired
private DataSource dataSource;
@GetMapping("show")
public String test(){
return "hello";
}
}
debug启动,启动服务的时候就会执行构造方法