继承变量上的@ConfigurationProperties [英] @ConfigurationProperties on inherited variable
问题描述
我有一个看起来像这样的超类
I have a superclass that looks like this
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
时,我收到一个无法强制转换的异常.
When I try to cast CustomProvider.getAccount()
from ProviderAccount
to CustomProviderAccount
I get an exception that I cannot cast.
引起:java.lang.ClassCastException:com.example.bean.hrs.ProviderAccount 不能转换为com.triphop.bean.hrs.CustomProviderAccount 在com.triphop.service.HRSServiceImpl.test(HRSServiceImpl.java:205) 在sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)在 java.lang.reflect.Method.invoke(Method.java:498)
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 中实现这一目标吗?
Any idea how can I achieve this in Spring?
推荐答案
@ConfigurationProperties
注释不是 @Inherited
.您需要在您的子类中定义它以实现您想要做的事情.
The @ConfigurationProperties
annotation isn't @Inherited
. You would need to define it on your child class to achieve what you are looking to do.
https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html
您可以为值创建一个通用包装器,并为每种类型的 provider
创建一个 Map,而不是使用扩展.
Rather than using extension you could just create a generic wrapper for the values and create a Map for each type of provider
.
这篇关于继承变量上的@ConfigurationProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!