如何使用Spring 3.0 Services实现Factory Pattern [英] how to implement Factory Pattern with Spring 3.0 Services

查看:49
本文介绍了如何使用Spring 3.0 Services实现Factory Pattern的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有一个带有org.springframework.stereotype.Service标记的接口。

In my project I have an interface annotated with org.springframework.stereotype.Service tag.

此接口有两种不同的实现。

I have two different implementation for this interface.

在我的管理bean中,我正在注入接口Service类并使用其方法。

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.

根据我的理解,我们可以使用Factory模式来实现此目的Java并达到相同的目的。

As per my understanding, we can achieve this using Factory pattern in java and achieve the same.

我们如何在SPRIng中实现呢?

How can we implement this in SPRIng???

推荐答案

除了上面建议的相关主题外,还有一个很好的

Besides suggested related topic above, there is a good thread on JavaRanch.

您可以使用


  1. @Qualifier( myServiceImpl1)注释以及@Autowired。在
    中,接口的这种特定实现将注入
    。您还应该在@ Component,
    @Service或@Repository注释中使用相同的名称,例如

  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;
}


  • @Primary与@ Component,@ Service或@Repository $在实现类中添加b $ b注释,在这种情况下,默认情况下将注入此
    实现。

  • @Primary together with @Component, @Service or @Repository annotations in your implementation class, in that case this implementation will be injected by default.

    如果标记某些接口的列表类型为@Autowired,将注入该接口的所有
    可用实现。

    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; 
    


  • 这篇关于如何使用Spring 3.0 Services实现Factory Pattern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆