我正在使用 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 注入(inject)属性的顺序,使用 @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;
}
}
这可以实现三件事:
- 默认为 9999
- 如果
server.port
不为空,则使用它 - 如果用户在
application.properties
文件中指定myapp.port
,请使用它(Spring 在加载@Bean
后注入(inject)它)
关于java - Spring Boot - 基于其他属性自动配置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538171/