【问题标题】:How to use @Autowired to dynamically inject implementation like a factory pattern如何使用@Autowired 像工厂模式一样动态注入实现
【发布时间】:2011-04-20 03:37:12
【问题描述】:

我是 Sprint 的新手,我的应用程序使用 Spring 3.x 和 roo1.1.1。

我有一个接口的多个实现,可以@Autowired 到其他不同的类中。我只能在运行时决定使用哪个实现。这应该通过类似工厂模式来实现。

public interface SomeInterface {
    public void doSomething();
}

实施 1.

public class SomeOb implements SomeInterface {
    public void doSomething() {
        //Do something for first implementation here
    }
}

实施 2.

public class SomeOtherOb implements SomeInterface {
    public void doSomething() {
        //Do something for first implementation here
    }
}

现在在我的服务中,我需要像这样的 Autowired

@Service 
public class MyService {

   @Autowired
   SomeInterface ob;
   //Rest of the code here

}

1) 选择要自动装配的实现的逻辑只知道运行时,所以我不能使用@Qualifier 注释来限定它。 2)我试图创建一个像

的 FactoryBean
public class SomeFactoryBean implements FactoryBean<SomeInterface> {
@Override
public SomeInterface getObject() throws Exception {
    if(/*Somecondition*/) {
        return new SomeOb();
    } else
        return new SomeOtherOb();
}

@Override
public Class<? extends SomeInterface> getObjectType() {
    if(/*Somecondition*/) {
        return SomeOb.class;
    } else
        return SomeOtherOb.class;
}

@Override
public boolean isSingleton() {
    return false;
}
}

在 applicationContext.xml 中我提到了标签。

当我运行网络服务器时,我遇到了类似的错误

No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory]

谁能帮我解决这个问题。如果我做的不对,请指导我以正确的方式做。

感谢并感谢任何帮助, jjk

【问题讨论】:

    标签: spring autowired


    【解决方案1】:

    感谢您的建议。我在同事的帮助下解决了这个问题。我做错了什么

    1. 我使用@Service 实现了 SomeInterface。所以这被弹簧扫描仪拾取并添加到 bean 中。
    2. 在反复试验期间,我从 FactoryBean 实现中删除了 @Component 注释。

    进行这些更改后,它就像一个魅力。

    【讨论】:

      【解决方案2】:

      如果您的应用程序的给定实例只需要 bean 的一个实现,则从 isSingleton() 返回 true

      但我质疑你的设计。

      我总是使用属性文件来切换这样的实现。我曾经不得不为一个网站实施验证码集成。我们使用 JCaptcah 和 ReCAPTCHA API 进行原型设计。我创建了一个只包含我们需要的功能的新接口,然后为这两个 API 创建了实现。在 Spring 配置文件和 Maven 配置文件中使用占位符,我们可以在编译时或部署时切换实现类,例如 mvn jetty:run -DcaptchaImpl=recaptcha 或 -DcaptchaImpl=jcaptcha。

      在不知道自己想要完成的任务的情况下,很难提供更多建议。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-14
        • 2016-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        相关资源
        最近更新 更多