How can I use YAML properties with constructor introduction in Spring Boot?

I know that it should be a piece of cake, but I just donโ€™t get anything.

In my Spring boot application, in the application.yml file, I have an entry like:

some: constructor: property: value 

And I have a Spring service (this is fake, but demonstrates the problem):

 package somepackage; @Service public class DummyService { public DummyService(@Value("${some.constructor.property}") String path) {} } 

The launch failed:

org.springframework.beans.factory.BeanCreationException: error creating a bean with the name "dummyService" defined in the file [... (class file) ...]: Error creating bean; nested exception org.springframework.beans.BeanInstantiationException: failed instantiate [somepackage.DummyService]: default constructor not found; The nested exception is java.lang.NoSuchMethodException: somepackage.DummyService. ()

How can I convince Spring that it should use a non-empty constructor, and it should get this constructor parameter from the YAML file? Note. I do not use XML bean configuration files or anything else, and would not want to.

+6
source share
2 answers

Just put the @Autowired annotation on your constructor.

 @Autowired public DummyService(@Value("${some.constructor.property}") String path) {} 
+2
source

And just in case, someone is trying to do this in Scala - this is what I really tried to do, but wanted to get an answer in Java before trying it with Scala - this works:

 @Service class DummyService @Autowired()(@Value("${some.constructor.property}") val path: String) { } 

This is described in this case, SO, for auto-negotiation of the Scala constructor.

0
source

All Articles