title: Spring injects a one-element Set instead of an empty Set
body: <p>We have an application where we are trying to inject an empty <code>java.util.HashSet</code> into a member of type <code>java.util.Set</code>, in a class which itself is a <code>@Component</code>. Spring seems to inject a <code>HashSet</code> with one element of the containing type. Any idea why Spring doesn't just inject an empty set?</p>
  
  <p><strong>Set element class:</strong></p>
  
  <pre><code>@Component
  public class SetElement
  {
      private String value;
  
      public String getValue()
      {
          return value;
      }
  }
  </code></pre>
  
  <p><strong>Class that contains a Set as a member:</strong></p>
  
  <pre><code>@Component
  public class MyClassWithSet
  {
      @Autowired
      private Set&lt;SetElement&gt; setOfElements;
  
      protected void setStringSet(Set&lt;SetElement&gt; stringSet)
      {
          this.setOfElements = stringSet;
      }
  
      public Set&lt;SetElement&gt; getStringSet()
      {
          return Collections.unmodifiableSet(setOfElements);
      }
  }
  </code></pre>
  
  <p><strong>Spring.xml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;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
      "&gt;
  
      &lt;bean id="setOfElements" class="java.util.HashSet" /&gt;
      &lt;context:component-scan base-package="com.vikdor.db " /&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p><strong>Sample test case to confirm the behavior</strong></p>
  
  <pre><code>@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());
      }
  
  }
  </code></pre>