java - 继承变量上的@ConfigurationProperties

标签 java spring spring-boot

我有一个看起来像这样的父类(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()时来自ProviderAccountCustomProviderAccount我遇到无法转换的异常。

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.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,而不是使用扩展。

关于java - 继承变量上的@ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512517/

相关文章:

java - JBoss 7 覆盖 JNDI 数据源

java - 如何将类路径添加到 Gradle JavaExec 任务以执行可运行的 jar?

java - 我如何以编程方式为 Spring Boot 和 Tomcat 提供 keystore 文件?

java - 如何构建具有网页之间共享功能的 Spring Controller

java - 我的所有 JUnit 都出现空指针异常。调试中 - 未找到源

java - 以最高安全设置运行java

java - 检查是否存在具有相同属性的对象 - 静态工厂方法

java - IBM Websphere MQ - 用于 Tomcat 部署的 EJB 和 MDB 迁移

java - 如何使 localhost Rest api 与 React-Native 一起工作?

java - Spring Boot 1.5.2 启动 : java. lang.NoSuchMethodError : javax. servlet.ServletContext.getVirtualServerName()Ljava/lang/String;