简体   繁体   中英

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.

Just put the @Autowired annotation on your constructor.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM