问题
In my project I have an interface annotated with org.springframework.stereotype.Service tag.
I have two different implementation for this interface.
In my manage bean, I am injecting interface Service class and using its methods.
Now my requirement is, in run time I have to pick particular implementation (lets say based on login user group) so that respective logic can be invoked.
As per my understanding, we can achieve this using Factory pattern in java and achieve the same.
How can we implement this in SPRIng???
回答1:
Besides suggested related topic above, there is a good thread on JavaRanch.
You can use
@Qualifier("myServiceImpl1") annotation together with @Autowired. In that case this particular implementation of the interface will be injected. You should also use the same name with your @Component, @Service or @Repository annotations e.g.
@Service("myServiceImpl1") public class MyServiceImpl1 implements MyService{} public class Consumer{ @Autowired @Qualifier("myServiceImpl1") public MyService myServiceImpl1; }@Primary together with @Component, @Service or @Repository annotations in your implementation class, in that case this implementation will be injected by default.
If you mark a list of some interface type with @Autowired, all available implementations of this interface will be injected.
@Autowired public List<MyService> allAvailableImplementations;
来源:https://stackoverflow.com/questions/12338138/how-to-implement-factory-pattern-with-spring-3-0-services