[英]How to inject properties from application.yml file?
I have some application.yml file:我有一些 application.yml 文件:
main-prop:
sub-prop:
name: test
password: test1
data:
prop1: 1
prop2: 0
and classes:和课程:
abstract class abscractPropertyHolder {
private String namePattern;
private String categoryPattern;
private String departmentPattern;
private Data data;
}
@Component
@ConfigurationProperties("main-prop")
class ReconfigurationEventFilterConfig extends abscractPropertyHolder {
}
@Data
@Accessors(chain = true)
class Data { // if my class is public - my app run successfully, otherwise fail to start (exception).
private int prop1;
private int prop2;
static DatanewInstanceWithDefaultParameters() {
return new Data().setProp1(1).setProp2(0);
}
}
I have this exception:我有这个例外:
Could not instantiate property type [com.test.Data] to auto-grow nested property path;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.test.Data]: Is the constructor accessible?;
nested exception is java.lang.IllegalAccessException:
Class org.springframework.beans.BeanUtils can not access a member of class
com.test.Data with modifiers "public"
All classes places in the one package.所有类都放在一个包中。 I don't want to make my Data class public.我不想公开我的数据类。 How can I inject data from application.yml?如何从 application.yml 注入数据?
I fixed the problem like this:我解决了这样的问题:
I added the spring annotation @Autowired
to the abscractPropertyHolder class and added spring annotation @ConfigurationProperties("main-prop.sub-prop.data")
to the Data class.我在 abscractPropertyHolder 类中添加了 spring 注释@Autowired
并在 Data 类中添加了 spring 注释@ConfigurationProperties("main-prop.sub-prop.data")
。
abstract class abscractPropertyHolder {
private String namePattern;
private String categoryPattern;
private String departmentPattern;
@Autowired
private Data data;
}
@Data
@Accessors(chain = true)
@ConfigurationProperties("main-prop.sub-prop.data")
class Data { // if my class is public - my app run successfully, otherwise fail to
start (exception).
private int prop1;
private int prop2;
static DatanewInstanceWithDefaultParameters() {
return new Data().setProp1(1).setProp2(0);
}
}
Format yml like this:像这样格式化 yml:
main-prop:
sub-prop:
name: test
password: test1
data:
prop1: 1
prop2: 0
@Data
makes use of @RequiredArgsConstructor
. @Data
使用@RequiredArgsConstructor
。 Try to define the behaviour of the @Data
annotation by overriding the visibility of the constructor it creates:尝试通过覆盖它创建的构造函数的可见性来定义@Data
注释的行为:
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
Having @Data
and @RequiredArgsConstructor
, Lombok will use the access level you define.有了@Data
和@RequiredArgsConstructor
,Lombok 将使用您定义的访问级别。
Either this or try to define a @NoArgsConstructor
.或者尝试定义一个@NoArgsConstructor
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.