Java 显式定义构造函数时,类中未定义具有0个参数的构造函数
我不明白。。。我实际上定义了构造函数,但是我得到了Java 显式定义构造函数时,类中未定义具有0个参数的构造函数,java,spring,constructor,Java,Spring,Constructor,我不明白。。。我实际上定义了构造函数,但是我得到了 类中未定义具有0个参数的构造函数 @Component public class CustomMessageSource extends ReloadableResourceBundleMessageSource { public CustomMessageSource(Locale locale){ this.propertiesHolder = getMergedProperties(locale);
类中未定义具有0个参数的构造函数
@Component
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {
public CustomMessageSource(Locale locale){
this.propertiesHolder = getMergedProperties(locale);
this.properties = propertiesHolder.getProperties();
}
//... other setting, getters
这就是我实例化它的方式
CustomMessageSource customMessage=新的CustomMessageSource(语言环境)代码>
这是我的堆栈跟踪
Caused by: java.lang.NoSuchMethodException: com.app.service.CustomMessageSource.<init>()
at java.lang.Class.getConstructor0(Class.java:3074)
at java.lang.Class.getDeclaredConstructor(Class.java:2170)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
... 38 more
原因:java.lang.NoSuchMethodException:com.app.service.CustomMessageSource。()
位于java.lang.Class.getConstructor0(Class.java:3074)
位于java.lang.Class.getDeclaredConstructor(Class.java:2170)
位于org.springframework.beans.factory.support.SimpleInstallationStrategy.instantiate(SimpleInstallationStrategy.java:80)
... 38多
默认情况下,Spring希望通过反射实例化无参数构造函数:
com.app.service.CustomMessageSource.<init>()
如果使用Spring4.3或更高版本,则使用单个构造函数声明的bean不需要指定@Autowired
注释。
来源:在Java中,您可以定义多个构造函数。默认情况下,如果要添加带参数的构造函数,必须首先定义无参数构造函数。
因此,您的代码将如下所示:
@Component
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {
public CustomMessageSource() {}
public CustomMessageSource(Locale locale){
this.propertiesHolder = getMergedProperties(locale);
this.properties = propertiesHolder.getProperties();
}
//... other setting, getters
}
构造函数具有1
参数,而不是0
。如果您想要一个0
参数构造函数,并且您至少定义了一个构造函数,那么您需要自己编写一个0
参数构造函数。Java将提供一个0
参数构造函数(默认构造函数),当且仅当您根本没有编写任何构造函数时。@Turing85正确,但添加无参数构造函数似乎不合适,因为它将阻止创建一个CustomMessageSource
实例,该实例的状态由定义了参数的构造函数保证一致。将@Autowired
放在构造函数上(或使用Spring4.3)告诉Spring使用哪一个,否则它需要一个默认的无参数构造函数。
@Component
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {
public CustomMessageSource() {}
public CustomMessageSource(Locale locale){
this.propertiesHolder = getMergedProperties(locale);
this.properties = propertiesHolder.getProperties();
}
//... other setting, getters
}