Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 263
user1953555 Avatar asked Nov 25 '15 22:11

user1953555


1 Answers

Just put the @Autowired annotation on your constructor.

@Autowired
public DummyService(@Value("${some.constructor.property}") String path) {}
like image 155
Mohit Avatar answered Sep 28 '22 08:09

Mohit