InterviewSolution
| 1. |
Explain various @Conditional Annotations in Spring Boot. |
|
Answer» For Class level conditions, you can have @ConditionalOnClass and @ConditionalOnMissingClass. The @ConditionalOnClass and @ConditionalOnMissingClass annotations let @Configuration classes be included based on the presence or absence of specific classes. For example, using these conditions, Spring will only use configuration MyConfiguration bean if the SomeClass is present on the classpath: @Configuration @ConditionalOnClass(SomeClass.class) class MyConfiguration { //... }Similarly, in the following example, Spring will only use configuration MyConfiguration bean if the SomeClass is absent on classpath: @Configuration @ConditionalOnMissingClass(SomeClass.class) class MyConfiguration { //... }Similarly, there is something called, @ConditionalOnBean and @ConditionalOnMissingBean. If the beans specified as PART of this annotation are available on classpath then class will be considered for Configuration. @Bean @ConditionalOnBean(name = "dependentBean") Mybean myBean() { // ... }Here MyBean will be created only if dependentBean exists on classpath, this is very useful to create bean in ApplicationContext. @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { ... } }Here if myService bean will be created only if no existing my service bean exists in ApplicationContext. @ConditionalOnProperty This tells Spring to INCLUDE Configuration based on PROPERTY value. This can come to rescue for defining environment-specific beans. In the following example, the instance of MyBean will be created only if = local. @Bean @ConditionalOnProperty( name = "usemysql", havingValue = "local" ) MyBean myBean() { // ... }If you want to include configuration if a specific resource is present, then you can use @ConditionalOnResource is present. The @ConditionalOnResource annotation lets configuration be included only when a specific resource is present: @ConditionalOnResource(resources = "classpath:myproperties.properties") Properties myProperties() { // ... }Let’s consider a situation, where you WOULD LIKE to include a particular configuration only if the application is a web application. In such cases, you can use @ConditionalOnWebApplication annotation. @ConditionalOnWebApplication MyController myController() { // ... }Similarly, we have @ConditionalOnNotWebApplication which can be used to include configuration if the application is non-web application. We have seen various @Condition annotation which are for specific use cases. If we have a general and more complex requirement, we can make use of @Conditional annotation & @ConditionalExpression annotation. @Bean @ConditionalOnExpression("${isProduction} && ${myserver == weblogic}") DataSource dataSource() { // ... } |
|