我有一个看起来像这样的父类(super class)
public class MyProvider {
private Integer id;
private ProviderAccount account;
}
扩展类
@Component
@ConfigurationProperties(prefix = "provider.custom")
public class CustomProvider extends MyProvider {
//this should have CustomProviderAccount
}
provider.custom
的配置
provider.custom.account.index=1
provider.custom.account.enabled=false
provider.custom.account.description=New Live
帐户类别
public class ProviderAccount {
private Integer index;
}
public class CustomProviderAccount extends ProviderAccount {
private boolean enabled;
private String description;
}
当我尝试转换CustomProvider.getAccount()
时来自ProviderAccount
至CustomProviderAccount
我遇到无法转换的异常。
Caused by: java.lang.ClassCastException: com.example.bean.hrs.ProviderAccount cannot be cast to com.triphop.bean.hrs.CustomProviderAccount at com.triphop.service.HRSServiceImpl.test(HRSServiceImpl.java:205) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498)
知道如何在 Spring 中实现这一目标吗?
最佳答案
@ConfigurationProperties
注释不是 @Inherited
。您需要在您的子类上定义它才能实现您想要做的事情。
https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html
您可以为值创建一个通用包装器,并为每种类型的provider
创建一个Map,而不是使用扩展。
关于java - 继承变量上的@ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512517/