それ自体がであるクラスで、java.util.HashSet
タイプのメンバーに空を注入しようとしているアプリケーションがあります。Springは、包含タイプの1つの要素を注入しているようです。Springが空のセットを注入しない理由はありますか?java.util.Set
@Component
HashSet
要素クラスを設定します。
@Component
public class SetElement
{
private String value;
public String getValue()
{
return value;
}
}
メンバーとしてセットを含むクラス:
@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);
}
}
Spring.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());
}
}