繁体   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