繁体   English   中英

在显式定义构造函数时,没有在类中定义0参数的构造函数

[英]No constructor with 0 arguments defined in class when explicitly define constructor

我不明白......我实际上定义了构造函数,但我得到了

No constructor with 0 arguments defined in class

@Component
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {

public CustomMessageSource(Locale locale){

    this.propertiesHolder = getMergedProperties(locale);        

    this.properties = propertiesHolder.getProperties();
}
//... other setting, getters

这就是我实例化它的方式

CustomMessageSource customMessage = new CustomMessageSource(locale);

这是我的堆栈跟踪

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

默认情况下,Spring希望通过反射来实例化no arg构造函数:

 com.app.service.CustomMessageSource.<init>()

通过在构造函数中指定@Autowired ,它应该工作:

@Autowired
public CustomMessageSource(Locale locale){

如果使用Spring 4.3或更高版本,则使用单个构造函数声明的bean不需要指定@Autowired批注。 资料来源: https//spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3

在Java中,您可以定义多个构造函数。 默认情况下,如果要添加带参数的构造函数,则必须首先定义无参数构造函数。 所以你的代码看起来像:

@Component
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {

        public CustomMessageSource() {} 
        public CustomMessageSource(Locale locale){

            this.propertiesHolder = getMergedProperties(locale);        

            this.properties = propertiesHolder.getProperties();
        }
       //... other setting, getters
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM