gpt4 book ai didi

java - 如何定义用于 的自定义 Set 实现

转载 作者:行者123 更新时间:2023-12-01 15:40:32 27 4
gpt4 key购买 nike

在使用 Spring 时,我遇到了一个奇怪的问题。我有一个类,它接受一个集合作为输入,因为该类是底层框架的,所以我无法更改它。这是它的声明

private Set evaluate;

public Set getEvaluate()
{
return evaluate;
}

public void setEvaluate(Set evaluate)
{
this.evaluate = evaluate;
}

我是 spring 文件,我有以下条目

<bean id="customService"
class="com.platform.impl.DefaultFrameworkService"
scope="tenant" parent="abstractService">
<property name="evaluate">
<set>
<ref bean="bean1" />
<ref bean="bean2" />
<ref bean="bean3" />
<!-- inject new bean here. -->
<ref bean="bean4" />
</set>
</property>

这里DefaultFrameworkService将 set 作为输入。所以我所做的就是向底层服务注入(inject)一个新的 bean。

我的问题是当 spring 读取这个文件时它会转换这个 <set> sprong.xml 条目为 LinkedHashSet并尝试将这些值设置为 private Set evaluate最终抛出异常。

虽然我总是可以覆盖 DefaultFrameworkService然后可以将其转换为 LinkedHashSet设置但想寻找更好的方法。

我得到的异常(exception)是

Failed to convert property value of type 'java.util.LinkedHashSet' to required type 'java.util.Set' for property 'evaluate'

我怎样才能让 spring 仅以 set 的形式传递值?而不是LinkedHashSet

更新

我无法设置所有这些,所以我尝试了一下创建了一个新的自定义类,即 CustomDefaultFrameworkService具有以下实现

public class CustomDefaultFrameworkService extends DefaultFrameworkService
{

Logger log = Logger.getLogger(CustomDefaultFrameworkService.class);
@SuppressWarnings("unused")
private Set evaluate;

/**
* @param evaluateStrategies
* the evaluateStrategies to set
*/
@Override
public void setEvaluate(final Set evaluate)
{
log.info("Setting values to super class. Total values being injected are " + evaluateStrategies.size());
super.setEvaluate(evaluate);

}
}

我可以将 map 设置为父类(super class)。这件事让我更加困惑。

最佳答案

使用util namespace ,它的元素 set 有一个参数 set-class,您可以在其中指定要使用的实现。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


<util:set id="emails" set-class="my.custom.set.implmentation">
<value>pechorin@hero.org</value>
<value>raskolnikov@slums.org</value>
<value>stavrogin@gov.org</value>
<value>porfiry@gov.org</value>
</util:set>

</beans>

@参见Spring Reference Chapter C.2.2.6

关于java - 如何定义用于 <set></set> 的自定义 Set 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8118237/

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