Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No constructor with 0 arguments defined in class when explicitly define constructor

I don't understand... I actually defined constructor but I am getting

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

This is how I instantiated it

CustomMessageSource customMessage = new CustomMessageSource(locale);

This is my stack trace

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
like image 909
Eric Huang Avatar asked Jul 11 '26 22:07

Eric Huang


1 Answers

By default, Spring wants to instantiate the no arg constructor by reflection :

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

By specifying @Autowired in the constructor, it should work :

@Autowired
public CustomMessageSource(Locale locale){

If you use Spring 4.3 or later, beans declared with a single constructor don't need to specify the @Autowired annotation. Source : https://spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3

like image 157
davidxxx Avatar answered Jul 13 '26 14:07

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!