Spring注入需要默认构造函数吗?

2023-11-23

我正在尝试注入一个带有一些参数的构造函数。编译 Spring 后抱怨找不到默认构造函数(我还没有定义它)并抛出 BeanInstatiationException 和 NoSuchMethodException。

定义默认构造函数后,异常不再出现,但是我的对象从未使用参数构造函数初始化,仅调用默认构造函数。在这种情况下,Spring 真的需要默认构造函数吗?如果是,我怎样才能让它使用参数构造函数而不是默认构造函数?

这就是我连接一切的方式:

public class Servlet {

  @Autowired
  private Module module;

  (code that uses module...)
}

@Component
public class Module {

  public Module(String arg) {}
  ...
}

豆配置:

<beans>
  <bean id="module" class="com.client.Module">
    <constructor-arg type="java.lang.String" index="0">
    <value>Text</value>
    </constructor-arg>
  </bean>

  ...
</beans>

堆栈跟踪:

WARNING: Could not get url for /javax/servlet/resources/j2ee_web_services_1_1.xsd
ERROR  initWebApplicationContext, Context initialization failed
[tomcat:launch] org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'module' defined in URL [...]: Instantiation of bean failed;  
nested exception is org.springframework.beans.BeanInstantiationException: Could not 
instantiate bean class [com.client.Module]: No default constructor found; nested 
exception is java.lang.NoSuchMethodException: com.client.Module.<init>()

如果您计划在不带任何参数的情况下实例化它,Spring 仅“需要”默认构造函数。

例如,如果你的班级是这样的;

public class MyClass {

  private String something; 

  public MyClass(String something) {
    this.something = something;
  }

  public void setSomething(String something) {
    this.something = something;
  }

}

你在 Spring 中这样设置它;

<bean id="myClass" class="foo.bar.MyClass">
  <property name="something" value="hello"/>
</bean>

你会得到一个错误。原因是 Spring 实例化了你的类new MyClass()然后尝试拨打电话setSomething(..).

因此,Spring xml 应该如下所示;

<bean id="myClass" class="foo.bar.MyClass">
  <constructor-arg value="hello"/>
</bean>

所以看看你的com.client.Module看看它是如何在 Spring xml 中配置的

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring注入需要默认构造函数吗? 的相关文章

随机推荐