how to implement Factory Pattern with Spring 3.0 Services

十年热恋 提交于 2019-12-11 16:22:27

问题


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

  1. @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;
    }
    
  2. @Primary together with @Component, @Service or @Repository annotations in your implementation class, in that case this implementation will be injected by default.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!