I am trying to write a ValidatorFactory
which will give me a validator based on its type
public Validator getNewValidator(ValidatorType type){
switch:
case a : new Validator1();
break;
case b : new Validator2();
break;
}
I want to write using spring xml beans definition
I can use method injection but it will let me create only one object and the method does
not take any arguments.
I don't want to use FactoryBean
.. I am just looking whether we can do this using spring xml
bean definition.
Another way of making the component conditional would be to place the condition directly on the component class: @Service @Conditional(IsDevEnvCondition. class) class LoggingService { // ... } We can apply the above example to any bean declared with the @Component, @Service, @Repository, or @Controller annotations.
Annotation Type ConditionalOnMissingBean. @Conditional that only matches when no beans meeting the specified requirements are already contained in the BeanFactory . None of the requirements must be met for the condition to match and the requirements do not have to be met by the same bean.
In Spring Boot, you can use the @ConditionalOnProperty annotation to enable or disable a particular bean based on the presence of a property. This is very useful if you want to provide optional features to your microservice. And that's it. Your optionalClass bean should resolve to null when you specify mybean.
Annotation Type Conditional The @Conditional annotation may be used in any of the following ways: as a type-level annotation on any class directly or indirectly annotated with @Component , including @Configuration classes. as a meta-annotation, for the purpose of composing custom stereotype annotations.
If you are using annotation (@Autowired
, @Qualifier
etc) instead of xml, you are not able to make conditional beans work (at least at current version 3). This is due to @Qualifier does not support expression
@Qualifier(value="${validatorType}")
More information is at https://stackoverflow.com/a/7813228/418439
you can do conditional bean injection with plain xml. The "ref" attribute can be triggered by property values from a property file and thus create conditional beans depending on property values. This feature is not documented but it works perfect.
<bean id="validatorFactory" class="ValidatorFactory">
<property name="validator" ref="${validatorType}" />
</bean>
<bean id="validatorTypeOne" class="Validator1" lazy-init="true" />
<bean id="validatorTypeTwo" class="Validator2" lazy-init="true" />
And the content of the property file would be:
validatorType=validatorTypeOne
To use the property file in your xml just add this context to the top of your spring config
<context:property-placeholder location="classpath:app.properties" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With