如何在Spring Boot中使用YAML属性和构造函数注入?

use*_*555 8 java spring dependency-injection spring-mvc spring-boot

我知道这应该是小菜一碟,但我只是无处可去.

在我的Spring Boot应用程序中,在application.yml文件中,我有一个这样的条目:

some:
    constructor:
        property: value
Run Code Online (Sandbox Code Playgroud)

我有一个弹簧服务(这是假的,但证明了问题):

package somepackage;

@Service
public class DummyService {
    public DummyService(@Value("${some.constructor.property}") String path) {}
}
Run Code Online (Sandbox Code Playgroud)

但是,启动失败了:

org.springframework.beans.factory.BeanCreationException:创建文件[...(类文件)中定义的名称为'dummyService'的bean时出错...]:bean的实例化失败; 嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[somepackage.DummyService]:找不到默认构造函数; 嵌套异常是java.lang.NoSuchMethodException:somepackage.DummyService.()

我怎么能说服Spring应该使用非空构造函数,它应该从YAML文件中获取构造函数参数?注意:我没有使用任何XML bean配置文件或任何东西,并且不愿意.

小智 6

只需将 @Autowired 注释放在构造函数上即可。

@Autowired
public DummyService(@Value("${some.constructor.property}") String path) {}
Run Code Online (Sandbox Code Playgroud)