继承变量的@ConfigurationProperties

时间:2017-10-01 12:49:44

标签: java spring spring-boot

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

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 at   com.triphop.service.HRSServiceImpl.test(HRSServiceImpl.java:205)at at   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)

任何想法如何在Spring中实现这一目标?

1 个答案:

答案 0 :(得分: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创建一个Map。