【问题标题】:Spring Boot - AutoConfigure properties based on other properties?Spring Boot - 基于其他属性的自动配置属性?
【发布时间】:2017-05-23 03:11:20
【问题描述】:

我正在使用 web Spring Boot 1.4.3 并创建一个自定义 @AutoConfigure 来设置一堆属性。事实证明,我设置的许多属性都依赖于一个内置的 Spring 属性:server.port。问题:让我的 AutoConfigurers 使用此属性(如果存在)的最佳方法是什么,否则默认为 9999?

这是我使用属性文件的方法:

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

这是我在 AutoConfiguration 方面取得的成就:

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

    Integer port = serverProperties.getPort() otherwise 9999?

}

我曾考虑使用 @PostConstruct 来执行逻辑,但查看 Spring-Boot 的自动配置源代码示例,我没有看到他们这样做,所以感觉就像代码异味。

【问题讨论】:

  • 不幸的是,您没有像 Java 编译器的注释传递那样获得迭代自动配置。您是否尝试过使用@AutoConfigureAfter
  • Integer port = serverProperties.getPort() != null?serverProperties.getPort():9999

标签: java spring-boot


【解决方案1】:

终于明白了!关键是使用@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;
    }
}

这可以实现 3 件事:

  1. 默认为 9999
  2. 如果server.port 不为空,则使用它
  3. 如果用户在application.properties 文件中指定myapp.port,请使用它(Spring 在加载@Bean 后将其注入)

【讨论】:

    【解决方案2】:

    自 Spring 3.x 以来,我个人更喜欢 @Value 注释(我相信)。

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

    如果您在application.properties 中设置server.port,它将使用其中设置的值。否则,它将默认为 9999。

    【讨论】:

    • 哦,它是 Spring Boot 1.4.3 而不是 4.3(如果我听起来像有强迫症的人,请道歉)
    • 感谢您对 4.3 Spring 版本的评论 - 我已将其更新到 1.4.3。
    • 我最终使用了@ConfigurationProperties@Autoconfigure,因为我需要在设置器中执行比简单的 9999 更复杂的逻辑,但鉴于我最初的问题,这是最好的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-04-21
    • 2018-11-14
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2020-12-21
    相关资源
    最近更新 更多