【问题标题】:Spring injection not working for constructor-arg弹簧注入不适用于构造函数-arg
【发布时间】:2012-05-08 05:35:19
【问题描述】:

我有以下 java 类:

package configuration;
import common.config.ConfigurationService;

public class AppConfig {

    private ConfigurationService configurationService;  

    public AppConfig(ConfigurationService configurationService){
        this.configurationService = configurationService;
    }

还有

public class ConfigurationServiceImpl
  implements ConfigurationService, Runnable
{...

应用上下文文件如下:

<bean id="appConfig" class="configuration.AppConfig" scope="prototype">
        <constructor-arg ref="configurationService"></constructor-arg>
    </bean>

    <bean id="configurationService"  class="common.config.ConfigurationServiceImpl" scope="singleton" />
    <bean id="propertyPlaceholderConfigurer"    class="common.config.PropertyPlaceholderConfigurer">
        <constructor-arg ref="configurationService" />
        <constructor-arg ref="serviceName" />
    </bean>

     <bean id="serviceName" class="java.lang.String"><constructor-arg value="filter"/></bean>  

在初始化期间,我收到以下错误,并且我的 bean 未初始化:

原因:org.springframework.beans.factory.BeanCreationException:创建在类路径资源 [conf/applicationContext.xml] 中定义的名称为“appConfig”的 bean 时出错:指定了 1 个构造函数参数,但在 bean 'appConfig 中找不到匹配的构造函数'(提示:为简单参数指定索引和/或类型参数以避免类型歧义)

如果我将 java 类代码修改如下,则 Spring 注入有效:

package configuration;
import common.config.ConfigurationServiceImpl;

    public class AppConfig {

        private ConfigurationServiceImpl configurationService;  

        public AppConfig(ConfigurationServiceImpl configurationService){
            this.configurationService = configurationService;
        }

【问题讨论】:

  • 当它开始为您工作时,您更新了什么。你能指出来吗?
  • @Zaheer 当我更改 AppConfig 类时。
  • 您使用的是什么版本的 spring,通过接口(代理)进行的依赖注入是否可以在您的应用程序中的任何位置工作,您是否有任何其他实例在您的应用程序中实现 ConfigurationService?
  • 你可以试试&lt;constructor-arg index="0" ref="configurationService"/&gt; 吗?
  • 我试图重现你的问题,但我不能,Impl 类被注入到构造函数中,期望接口没有任何问题......

标签: java spring


【解决方案1】:

首先,您必须知道Spring do not support interface injection,,这就是为什么您的第一种情况下的代码不起作用的原因,因为您传递的是作为构造函数参数的接口 ConfigurationService。

在第二种情况下,您通过传递 ConfigurationService 的实现类并将其作为构造函数参数来做到这一点。

【讨论】:

  • 这完全是错误的 - stackoverflow.com/questions/2387431/…
  • @chrismarx Spring 不支持通过构造函数参数 XML 配置注入接口。您的链接是关于使用接口类型引用和自动装配注释进行自动装配的问题。在这种情况下,它只有在可以找到自动装配到该接口的候选(实现)时才有效。如果没有实现,则从技术上讲,在该场景中不支持接口注入。所以不,tito 并不是“完全错误”。
【解决方案2】:

看一看,Spring配置中AppConfig的包名与Java源码中声明的包名不符。您有“common.config”与“配置”。可能是错误文本有误导性,找不到构造函数的原因是找不到类本身。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2018-01-17
    • 1970-01-01
    • 2022-01-05
    • 2015-05-14
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多