Reputation: 115
I know this should be a piece of cake but I'm just not getting anywhere.
In my Spring Boot app, in the application.yml file, I have an entry like so:
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) {}
}
Startup fails, though:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dummyService' defined in file [...(the class file)... ]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [somepackage.DummyService]: No default constructor found; nested exception is java.lang.NoSuchMethodException: somepackage.DummyService.()
How can I convince Spring that it should use the non-empty constructor, and it should get that constructor parameter from the YAML file? Note: I'm not using any XML bean config files or anything, and would prefer not to.
Upvotes: 8
Views: 6564
Reputation: 115
And just in case someone else is trying to do this in Scala -- which is what I was really trying to do, but wanted to get the answer in Java before trying it with Scala -- this works:
@Service
class DummyService @Autowired()(@Value("${some.constructor.property}") val path: String) {
}
This is covered in this SO case for scala constructor autowiring.
Upvotes: 0
Reputation: 1755
Just put the @Autowired annotation on your constructor.
@Autowired
public DummyService(@Value("${some.constructor.property}") String path) {}
Upvotes: 6