簡體   English   中英

Spring Boot-根據其他屬性自動配置屬性?

[英]Spring Boot - AutoConfigure properties based on other properties?

我正在使用Web Spring Boot 1.4.3並創建一個自定義@AutoConfigure來設置一堆屬性。 事實證明,我設置的許多屬性取決於一個內置的Spring屬性: server.port 問題:使我的自動配置器使用此屬性(如果存在)的最佳方法是什么,否則默認為9999?

這是我使用屬性文件執行的操作:

    myapp.port = ${server.port:9999}

這是我對自動配置的了解:

@Configuration(prefix="myapp")
@EnableConfigurationProperties(MyAppProperties.class)
public class MyAppProperties {
    @Autowired
    ServerProperties serverProperties;

    Integer port = serverProperties.getPort() otherwise 9999?

}

我曾考慮過使用@PostConstruct進行邏輯處理,但是在查看Spring-Boot的自動配置源代碼示例時,我沒有看到他們這樣做,因此感覺像是代碼氣味。

終於想通了! 關鍵是使用@Bean而不是@EnableConfigurationProperties(MyProps.class)公開我的依賴屬性。 由於Spring注入屬性的順序,使用@Bean可以讓我默認使用依賴的server.port屬性,同時仍允許application.properties文件覆蓋它。 完整示例:

@ConfigurationProperties(prefix="myapp")
public class MyProps {
    Integer port = 9999;
}

@AutoConfigureAfter(ServerPropertiesAutoConfiguration.class)
public class MyPropsAutoConfigurer {
    @Autowired
    private ServerProperties serverProperties;

    @Bean
    public MyProps myProps() {
        MyProps myProps = new MyProps();
        if (serverProperties.getPort() != null) {
            myProps.setPort(serverProperties.getPort());
        }
        return myProps;
    }
}

這實現了三件事:

  1. 默認為9999
  2. 如果server.port不為null,請使用
  3. 如果用戶在application.properties文件中指定了myapp.port ,請使用該文件(Spring會在加載@Bean之后注入它)

從Spring 3.x開始,我個人更喜歡@Value注釋(我相信)。

public class MyAppProperties {
    @Value("${server.port:9999}")
    private int port;
}

如果在application.properties設置server.port ,它將使用在那里設置的值。 否則,它將默認為9999。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM