我有一些application.yml文件:
main-prop:
sub-prop:
name: test
password: test1
data:
prop1: 1
prop2: 0
和课程:
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);
}
}
我有这个例外:
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"
所有类都放在一个包中。我不想公开我的数据类。如何从application.yml注入数据?
答案 0 :(得分:1)
我解决了这样的问题:
我在abscractPropertyHolder类中添加了弹簧注释@Autowired
,并在Data类中添加了弹簧注释@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);
}
}
答案 1 :(得分:0)
像这样格式化yml:
main-prop:
sub-prop:
name: test
password: test1
data:
prop1: 1
prop2: 0
答案 2 :(得分:0)
@Data
使用@RequiredArgsConstructor
。尝试通过覆盖其创建的构造函数的可见性来定义@Data
注释的行为:
@RequiredArgsConstructor(access = AccessLevel.PUBLIC)
Lombok具有@Data
和@RequiredArgsConstructor
,将使用您定义的访问级别。
要么这样做,要么尝试定义@NoArgsConstructor
。