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

我知道这应该是小菜一碟,但我只是没有到达任何地方.

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

some:
    constructor:
        property: value

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

package somepackage;

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

但是,启动失败了:

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.()

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

解决方法

只需将@Autowired注释放在构造函数上即可.
@Autowired
public DummyService(@Value("${some.constructor.property}") String path) {}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...