gpt4 book ai didi

java - 继承变量上的@ConfigurationProperties

转载 作者:行者123 更新时间:2023-11-30 06:28:59 25 4
gpt4 key购买 nike

我有一个看起来像这样的父类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com