Spring Auto-wiring
Assuming i have two classes Circle and Rectangle that implement an interface called Shape.
And i have the following class:public class ObjectFactory {
@Autowired
@Qualifier("circle")
Shape shape;
.......
.......
.......
}
What i want to do is to remove the @Qualifier and make the autowiring depend on some condition (for example if condition is true then inject Circle, if the condition is false, inject the rectangle) or make the wiring depend on a naming convention.
Is there a way to d开发者_开发问答o that ?Let me explain, If i remove the @Qualifier annotation, i'm going to end up with the following exception
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.app.objects.Shape] is defined:
expected single matching bean but found 2: [circle, rectangle]
Is there a way to handle programmatically that exception in order to have a condition dependent auto-wiring ?
You can use SpEL in @Resource
, perhaps you can use it in @Qualifier
as well.
But normally such logic can be placed in a FactoryBean
, where you can decide which instance to return.
精彩评论