| Condition annotations Except main @conditional annotation there are set of similar annotation to be used for different cases. Class conditions The @ConditionalOnClass and @ConditionalOnMissingClass annotations allows configuration to be included based on the presence or absence of specific classes. E.g. when OObjectDatabaseTx.class is added to dependencies and there is no OrientWebConfigurer bean we create the configurer. Bean conditions The @ConditionalOnBean and @ConditionalOnMissingBean annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value attribute to specify beans by type, or name to specify beans by name. The search attribute allows you to limit the ApplicationContext hierarchy that should be considered when searching for beans. See the example above when we check whether there is no defined bean. Property conditions The @ConditionalOnProperty annotation allows configuration to be included based on a Spring Environment property. Use the prefix and name attributes to specify the property that should be checked. By default any property that exists and is not equal to false will be matched. You can also create more advanced checks using the havingValue and matchIfMissing attributes. Resource conditions The @ConditionalOnResource annotation allows configuration to be included only when a specific resource is present. Web application conditions The @ConditionalOnWebApplication and @ConditionalOnNotWebApplication annotations allow configuration to be included depending on whether the application is a 'web application'. SpEL expression conditions The @ConditionalOnExpression annotation allows configuration to be included based on the result of a SpEL expression. Important point to note while using condition - The condition class is referred as direct class (not as spring bean) so it can't use the
@Value property injection i.e. no other spring beans can be injected within it. - From java docs - Conditions must follow the same restrictions as
BeanFactoryPostProcessor and take care to never interact with bean instances. The restrictions refereed here are A BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances. Doing so may cause premature bean instantiation, violating the container and causing unintended side-effects.
|