1

In Spring I can define a HashSet like so in XML:

<bean id="subscriberStore" class="java.util.HashSet"/>

And, I can do the following in the code to create a concurrent hash set:

subscriberStore = Collections.newSetFromMap(
                     new ConcurrentHashMap<Subscriber, Boolean>());

But is there any way I can do this in one step in the XML? E.g. something like:

 <bean id="subscriberStore" class="java.util.HashSet"/>
         <  Some code here to set subscriberStore to the result 
    of Collections.newSetFromMap(new ConcurrentHashMap<Subscriber, Boolean>?   >

Many Thanks!

manub
  • 3,990
  • 2
  • 24
  • 33
Rory
  • 1,805
  • 7
  • 31
  • 45

2 Answers2

4

Bean configuration:

<!-- The bean to be created via the factory bean -->
<bean id="exampleBean"
      factory-bean="myFactoryBean"
      factory-method="createInstance"/>

<bean id="myFactoryBean" class="com.rory.ConcurrentHashMapFactory"/>

And the factory class:

public class ConcurrentHashMapFactory {
  public Set<Subscriber> createInstance() {
    Collections.newSetFromMap(new ConcurrentHashMap<Subscriber, Boolean>());
  }
}
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

You could use something like the following:

<bean
    id="subscriberStore"
    class="java.util.Collections"
    factory-method="newSetFromMap"
>
    <constructor-arg>
        <bean class="java.util.concurrent.ConcurrentHashMap" />
    </constructor-arg>
</bean>

However, if generic types are important to you, create a custom, static factory method (as Boris Pavlović kind of suggests in his answer). You might want to take a look at this SO entry for some information regarding generics and Spring XML bean definitions.

Community
  • 1
  • 1
Go Dan
  • 15,194
  • 6
  • 41
  • 65