简体   繁体   中英

Spring Boot - AutoConfigure properties based on other properties?

I'm using web Spring Boot 1.4.3 and creating a custom @AutoConfigure to set a bunch of properties. It turns out many properties I set depend on one built-in Spring property: server.port . Question: What's the best way to make my AutoConfigurers use this property if it exists, otherwise default to 9999?

Here's how I do it with a properties file:

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

Here's how far I've gotten with AutoConfiguration:

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

    Integer port = serverProperties.getPort() otherwise 9999?

}

I've thought about using @PostConstruct to do the logic but looking at Spring-Boot's autoconfigure source code examples, I don't see them doing this so it feels like a code smell.

Finally figured it out! The key was to expose my dependent properties using @Bean rather than @EnableConfigurationProperties(MyProps.class) . Due to the order which Spring injects properties, using @Bean lets me default to the dependent server.port property while still letting application.properties file override it. Full example:

@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;
    }
}

This enables 3 things:

  1. Default to 9999
  2. If server.port is not null, use that
  3. If user specifies a myapp.port in an application.properties file, use that (Spring injects it after loading the @Bean )

I personally prefer the @Value annotation since Spring 3.x (I believe).

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

If you set server.port in application.properties , it'll use the value set in there. Otherwise, it'll default to 9999.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM