3

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 
3
  • 5
    Your constructor has 1 argument, not 0. If you want an 0 argument constructor and you defined at least one constructor, you need to write a 0 argument constructor yourself. Java will provide a 0 argument constructor (default-constructor), if and only if you did not write any constructor at all. Commented May 1, 2017 at 7:39
  • @Turing85 Right but adding a no arg constructor doesn't seem suitable since it will prevent from creating a CustomMessageSource instance with a consistent state guaranteed by the constructor with arg that is defined. Commented May 1, 2017 at 8:02
  • 1
    Put @Autowired on the constructor (or use Spring 4.3) to tell spring which one to use, else it expects a default no-args constructor. Commented May 1, 2017 at 8:20

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

In Java you can define multiple constructors. By default if you want to add a constructor with parameters, you have to define the parameterless constructor first. So your code will look like:

@Component public class CustomMessageSource extends ReloadableResourceBundleMessageSource { public CustomMessageSource() {} public CustomMessageSource(Locale locale){ this.propertiesHolder = getMergedProperties(locale); this.properties = propertiesHolder.getProperties(); } //... other setting, getters } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.