Search code examples
javaspringjakarta-eejava-ee-6

Java EE 6 injection to create different strategies


Say that I have class Controller with property strategy of type IStrategy. In Spring, I can create different instances of Controller and inject different strategy implementations by defining beans in xml configuration file as shown below:

<bean id="strategyAController" class="com.test.Controller"> 
    <property name="strategy" ref="strategyAImpl">
</bean>

<bean id="strategyBController" class="com.test.Controller"> 
    <property name="strategy" ref="strategyBImpl">
</bean>

<bean id="strategycController" class="com.test.Controller"> 
    <property name="strategy" ref="strategycImpl">
</bean>

I can then reference these beans using @Autowired and @Qualifier("strategyAController"), etc. What is the equivalent way of doing this in Java EE 6


Solution

  • Funny you should ask! Gavin King, who designed Java EE 6 CDI, got into a nasty fight with someone on exactly the same problem.

    http://www.tsolak.com/?p=59

    The Spring code, of course, looks awfully like Java. We can do that in java - create some variables, set some properties, no biggie. I am curious, in your perticular application, what's the drawback of doing it in plain Java? What's the specific benefit you get from Spring for these beans?