gpt4 book ai didi

spring - 如何使用@Autowired像工厂模式一样动态注入(inject)实现

转载 作者:行者123 更新时间:2023-12-02 09:00:23 25 4
gpt4 key购买 nike

我对 Sprint 相当陌生,我的应用程序使用 Spring 3.x 和 roo1.1.1。

我有一个接口(interface)的多个实现,该接口(interface)将被 @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)选择要 Autowiring 的实现的逻辑仅在运行时才知道,因此我无法使用 @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

最佳答案

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

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

进行这些更改后,它就像魅力一样发挥作用。

关于spring - 如何使用@Autowired像工厂模式一样动态注入(inject)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5725222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com