Spring The @ConfigurationProperties condition loads

I have an authentication service that I want to autoconfigure at runtime, but it will mock development and testing. I would like to use the @ConfigurationProperties function to determine the necessary parameters, but I also need to be able to conditionally create AuthenticationManager instances, depending on whether the live service is configured.

The approach I would like to use is to use something like @ConditionalOnBean(AuthProperties.class) , but Spring Boot creates a bean of my @ConfigurationProperties class regardless of whether the properties are present. I can apply validation annotations to fields, but then the context will not start at all if the live service is not configured.

Is there a clean way to make the configuration section conditional for the properties specified in the @ConfigurationProperties class without repeating the property names in @ConditionalOnProperty ?

+5
source share
2 answers

Can't you just use the profile of your application-some_profile.properties file and then create your bean properties conditionally like this

 @Profile("some_profile") @Component @ConfigurationProperties(prefix = "some.selector") public Class YourConfiguration{ private property option; } 

Thus, it is created only depending on which profile you choose on the air or bullying. Than you can use the selected profile for your @Configuration authentication classes for individual approaches or follow with @ConditionalOnBean. For which profiles, or maybe I misunderstood the question.

0
source

I had a similar problem and I could solve it using this approach using Spring Boot and Java 8, hope this helps someone:

 @Configuration @PropertySources({ @PropertySource("classpath:integration.properties"), @PropertySource(value = "classpath:integration-${spring.profiles.active}.properties", ignoreResourceNotFound = true) }) @ConfigurationProperties(prefix = "integration") public class IntegrationProperties { private String user; private String password; private String projectId; .... } 

integration.properties

 integration.user=User integration.password=Password integration.project-id=123 

integration-prod.properties

 integration.project-id=897 

Spring Boot will create a bean using the properties file, and for production (using the prod profile) it will use a different file and override the project-id . ignoreResourceNotFound = true will avoid a FileNotFoundException on startup if you are not using a prod profile.

0
source

Source: https://habr.com/ru/post/1210682/


All Articles