Sunday, January 19, 2020

There are many ways to use Configuration annotations in Spring Java application. @Configuration annotation is not the same as a bean. A POJO object defined as a configurationproperties can be imported into an  @configuration.
For example,
The proper annotations to use with Kubernetes secrets in Spring Java application: 
@Configuration 
@Primary 
@EnableWebSecurity 
@EnableConfigurationProperties(KubernetesSecrets.class) 
public class WebConfig extends WebSecurityConfigurerAdapter { 
    private static final Logger LOG = LoggerFactory.getLogger(WebConfig.class); 
    KubernetesSecrets secrets; 
    public WebConfig(KubernetesSecrets secrets) { 
        this.secrets = secrets; 
    } 
} 

Here the KubernetesSecrets object is a ConfigurationProperty which will get its values externally.
When a new instance of the KubernetesSecrets is created as part of this class in a method, that method will have an @Bean annotation. The same annotation does not hold for the above member variable and constructor

The differences between a Configuration, ConfigurationProperty and Bean are somewhat unclear when they are used merely to refer to an external source. The ConfigurationProperty is only a way to tell that these properties will have values defined externally.  The Configuration object is defined on an object that uses ConfigurationProperties.

Please note that we don't use @Autowired for the member variable or the constructor above. If it were a @Bean that would have been appropriate. 

A configuration is essential for context initialization which in turn helps the SpringBootApplication with initialization.

The @Bean is used to declare a single bean. Spring does it automatically when a @Component, @Service, or an @Repository is used because they come from classpath scanning.

No comments:

Post a Comment