【问题标题】:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helper' . No unique bean of type [java.lang.String]org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为 'helper' 的 bean 时出错。没有 [java.lang.String] 类型的唯一 bean
【发布时间】:2013-07-10 19:39:06
【问题描述】:

我想将一个字符串自动连接到构造函数。

我在 spring 配置 xml 中有这个:

<bean id="helper" class="test.Helper">
    <constructor-arg index="3" type="java.lang.String" value="http://test.com" />  
</bean>

Helper.java

@Component
public class Helper {
    private final ClientFactory clientFactory;
    private final ModelManager modelManager;
    private final SecurityService securityService;
    private final String url;

    @Autowired
    public Helper(ClientFactory clientFactory, ModelManager modelManager,
        SecurityService securityService, String url) {
        this.clientFactory = clientFactory;
        this.modelManager = modelManager;
        this.securityService = securityService;
        this.url = url;
    }
}

我收到错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有定义类型 [java.lang.String] 的唯一 bean:预期的单个匹配 bean 但找到 19:

感谢任何帮助。谢谢!

【问题讨论】:

  • 这里有一些冲突。您的Helper 类是@Component,但您也为它声明了bean。你最终会在你的上下文中得到两个 Helper 类的实例。
  • 我是弹簧菜鸟。那么如何只为 Helper 注入 url?其他参数也是组件。我尝试使用 "test"</value></constructor-arg> 。即使这样也没有用!我应该使用@Qualifier在构造函数中?

标签: java spring annotations autowired


【解决方案1】:

尝试在Ctor中删除@Autowired注解并在xml中进行配置:

<bean id="helper" class="test.Helper">
    <constructor-arg ref="clientFactory" />  
    <constructor-arg ref="modelManager" />  
    <constructor-arg type="java.lang.String" value="http://test.com" />  
    <constructor-arg ref="securityService" />  
</bean>

【讨论】:

    【解决方案2】:

    将索引属性与构造函数依赖一起使用。

    <bean id="helper" class="test.Helper">
        <constructor-arg index="0" ref="clientFactory" />  
        <constructor-arg index="1" ref="modelManager" />  
        <constructor-arg index="2" ref="securityService" />  
        <constructor-arg index="3" type="java.lang.String" value="http://test.com" />  
    </bean>
    

    这应该会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2021-11-17
      • 2021-08-25
      • 2021-08-13
      • 2018-11-03
      • 2021-09-18
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多