java - Spring 是否要求所有 bean 都具有默认构造函数?

标签 java spring spring-mvc default-constructor

我不想为我的 auditRecord 类创建默认构造函数。

但Spring似乎坚持这样做:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'auditRecord' defined in ServletContext resource
[/WEB-INF/applicationContext.xml]: 
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [com.bartholem.AuditRecord]: 
No default constructor found; 
nested exception is 
java.security.PrivilegedActionException:
java.lang.NoSuchMethodException: 
com.bartholem.AuditRecord

真的有必要吗?

最佳答案

不,您不需要使用默认(无 arg)构造函数。

你是如何定义你的 bean 的?听起来您可能已经告诉 Spring 实例化您的 bean,如下所示:

<bean id="AuditRecord" class="com.bartholem.AuditRecord"/>

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <property name="someProperty" val="someVal"/>
</bean>

您没有提供构造函数参数的地方。前一个将使用默认(或无 arg)构造函数。如果要使用接受参数的构造函数,则需要使用 constructor-arg 元素指定它们,如下所示:

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <constructor-arg val="someVal"/>
</bean>

如果您想在应用程序上下文中引用另一个 bean,您可以使用 constructor-arg 元素的 ref 属性而不是 val 属性。

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <constructor-arg ref="AnotherBean"/>
</bean>

<bean id="AnotherBean" class="some.other.Class" />

关于java - Spring 是否要求所有 bean 都具有默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492652/

相关文章:

java - 使用公共(public)接入点通过两个不同的网络传输文件

java - 是否可以使用 Spring Boot Mobile 为桌面和移动网站提供不同的index.html?

java - 在 Spring Security 中创建自定义 PostAuthorize 方法

java - Spring 单元测试: Autowire the Implementation of an Interface directly?

java - 无法在 Spring Boot 应用程序中使用 AWS SDK(套接字不是由该工厂创建的)

java在线编译器不同版本

java - Spring Boot 嵌入式 HornetQ 集群不转发消息

java - 计算文件中数字平均值的程序(涉及 try/catch block )

java - 使用 Spring MVC 的 REST web 服务在发布 JSON 时返回 null

javascript - MultipartFile 数组未发送到 spring Controller