11.類型安全的配置屬性

  • 使用@Value("${property}")注解注入配置屬性有時可能比較笨重,特別是需要使用多個properties或你的數據本身有層次結構。為了控制和校驗你的應用配置,Spring Boot提供一個允許強類型beans的替代方法來使用properties。

示例:

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
    private String username;
    private InetAddress remoteAddress;
// ... getters and setters
}
  • 當@EnableConfigurationProperties注解應用到你的@Configuration時,任何被@ConfigurationProperties注解的beans將自動被Environment屬性配置。這種風格的配置特別適合與SpringApplication的外部YAML配置進行配合使用。

    # application.yml
      connection:
        username: admin
        remoteAddress: 192.168.1.1
    # additional configuration as required
    
  • 為了使用@ConfigurationProperties beans,你可以使用與其他任何bean相同的方式注入它們。

      @Service
      public class MyService {
      @Autowired
      private ConnectionSettings connection;
      //...
      @PostConstruct
      public void openConnection() {
          Server server = new Server();
          this.connection.configure(server);
      }
      }
    
  • 你可以通過在@EnableConfigurationProperties注解中直接簡單的列出屬性類來快捷的注冊@ConfigurationProperties bean的定義。

    @Configuration
    @EnableConfigurationProperties(ConnectionSettings.class)
    public class MyConfiguration {
    }
    

注:使用@ConfigurationProperties能夠產生可被IDEs使用的元數據文件。

第三方配置
  • 正如使用@ConfigurationProperties注解一個類,你也可以在@Bean方法上使用它。當你需要綁定屬性到不受你控制的第三方組件時,這種方式非常有用。

  • 為了從Environment屬性配置一個bean,將@ConfigurationProperties添加到它的bean注冊過程:

     @ConfigurationProperties(prefix = "foo")
     @Bean
     public FooComponent fooComponent() {
     ...
     }
    
  • 和上面ConnectionSettings的示例方式相同,任何以foo為前綴的屬性定義都會被映射到FooComponent上。

松散的綁定(Relaxed binding)
  • Spring Boot使用一些寬松的規則用于綁定Environment屬性@ConfigurationProperties beans,所以Environment屬性名和bean屬性名不需要精確匹配。常見的示例中有用的包括虛線分割(比如,context--path綁定到contextPath)和將環境屬性轉為大寫字母(比如,PORT綁定port)。
    示例:

    @Component
    @ConfigurationProperties(prefix="person")
    public class ConnectionSettings {
    private String firstName;
    }
    

下面的屬性名都能用于上面的@ConfigurationProperties類:

屬性 說明
person.firstName 標準駝峰規則
person.first-name 虛線表示,推薦用于.properties和.yml文件中
PERSON_FIRST_NAME 大寫形式,使用系統環境變量時推薦
@ConfigurationProperties校驗
  • Spring Boot將嘗試校驗外部的配置,默認使用JSR-303(如果在classpath路徑中)。你可以輕松的為你的@ConfigurationProperties類添加JSR-303 javax.validation約束注解:

    @Component
    @ConfigurationProperties(prefix="connection")
    public class ConnectionSettings {
    @NotNull
    private InetAddress remoteAddress;
    // ... getters and setters
    }
    
  • 你也可以通過創建一個叫做configurationPropertiesValidator的bean來添加自定義的Spring Validator。

注:spring-boot-actuator模塊包含一個暴露所有@ConfigurationProperties beans的端點。簡單地將你的web瀏覽器指向/configprops或使用等效的JMX端點。具體參考Production ready features。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容