【问题标题】:@ConfigurationProperties on inherited variable继承变量的@ConfigurationProperties
【发布时间】:2018-03-12 18:10:45
【问题描述】:

我有一个看起来像这样的超类

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 时,我得到一个我无法转换的异常。

引起: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)

知道如何在 Spring 中实现这一点吗?

【问题讨论】:

  • 添加堆栈跟踪

标签: java spring spring-boot


【解决方案1】:

@ConfigurationProperties 注释不是@Inherited。您需要在您的子类上定义它以实现您想要做的事情。

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html

https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html

您可以只为值创建一个通用包装器并为provider 的每种类型创建一个映射,而不是使用扩展。

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 2015-12-09
    • 2014-10-06
    • 2016-06-01
    • 1970-01-01
    • 2018-08-13
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多