在Spring Boot中使用 @ConfigurationProperties 注解

 

使用mail做例子。配置放在mail.properties文件中。属性必须命名规范才能绑定成功。

Spring Boot 使用一些松的规则来绑定属性到@ConfigurationProperties bean 并且支持分层结构(hierarchical structure)。
开始创建一个@ConfigurationProperties bean:

 

@ConfigurationProperties(locations = "classpath:mail.properties", 
                         ignoreUnknownFields = false, 
                         prefix = "mail")
public class MailProperties { 
  public static class Smtp {  
    private boolean auth;  
    private boolean starttlsEnable;  
    // ... getters and setters 
  }
  @NotBlank private String host;
  private int port;  
  private String from; 
  private String username;
  private String password; 
  @NotNull private Smtp smtp; 
  // ... getters and setters
}

…从如下属性中创建 ( mail.properties ):

mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
mail.from=me@localhost
mail.username=
mail.password=

 



作者:crocodile_b
链接:http://www.jianshu.com/p/df57fefe0ab7
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文:http://www.jianshu.com/p/df57fefe0ab7

posted on 2017-08-10 17:19  轨道  阅读(168)  评论(0编辑  收藏  举报

导航