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

age*_*rrr 6 spring constructor dependency-injection autowired

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

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

这是我连接所有内容的方式:

public class Servlet {

  @Autowired
  private Module module;

  (code that uses module...)
}

@Component
public class Module {

  public Module(String arg) {}
  ...
}
Run Code Online (Sandbox Code Playgroud)

Bean配置:

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

  ...
</beans>
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

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>()
Run Code Online (Sandbox Code Playgroud)

inc*_*.de 8

如果您打算在没有任何参数的情况下实例化它,Spring只需要"默认构造函数".

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

public class MyClass {

  private String something; 

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

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

}
Run Code Online (Sandbox Code Playgroud)

你就像这样在Spring中设置它;

<bean id="myClass" class="foo.bar.MyClass">
  <property name="something" value="hello"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

你会得到一个错误.原因是Spring实例化你的类new MyClass()然后尝试设置调用setSomething(..).

所以相反,Spring xml应该是这样的;

<bean id="myClass" class="foo.bar.MyClass">
  <constructor-arg value="hello"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

所以看看你的com.client.Module,看看它在Spring xml中的配置方式


ike*_*ttu 6

很可能你正在使用组件扫描,因为你@Component为类Module 定义了注释,它试图实例化bean.@Component如果您使用XML进行bean定义,则不需要注释.