我们有一个应用程序,我们试图在java.util.HashSet
一个java.util.Set
本身是@Component
. Spring 似乎注入了HashSet
一个包含类型的元素。知道为什么 Spring 不只是注入一个空集吗?
设置元素类:
@Component
public class SetElement
{
private String value;
public String getValue()
{
return value;
}
}
包含 Set 作为成员的类:
@Component
public class MyClassWithSet
{
@Autowired
private Set<SetElement> setOfElements;
protected void setStringSet(Set<SetElement> stringSet)
{
this.setOfElements = stringSet;
}
public Set<SetElement> getStringSet()
{
return Collections.unmodifiableSet(setOfElements);
}
}
春天.xml
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="setOfElements" class="java.util.HashSet" />
<context:component-scan base-package="com.vikdor.db " />
</beans>
示例测试用例以确认行为
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
{ "classpath:META-INF/spring.xml" })
public class SpringSetTest
{
@Autowired
private MyClassWithSet myClassWithSet;
@Test
public void test()
{
assertNotNull(myClassWithSet);
assertNotNull(myClassWithSet.getStringSet());
assertTrue(myClassWithSet.getStringSet().isEmpty());
}
}