Announcement Announcement Module
Collapse
No announcement yet.
How to add Spring beans to a collection without method injection? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to add Spring beans to a collection without method injection?

    Hi all,

    I think I'm missing something very basic here and hope some of you can help me out.

    In my project, I need a collection of Spring beans based on the output of some other process. In plain Java, I'd do something like

    Code:
    // iterate over output
    List<aType> myList = new ArrayList<aTypeImpl>();
    for (String i : output) {
       // ... Process output ...
       myList.add(new aTypeImpl(i));
    }
    Now, I'd like to decouple this code from a particular implementation class (here aTypeImpl), but rather use Spring's factory for it.

    I successfully got this to work with method injection and "aTypeImpl" being of scope "prototype", so I define an abstract "lookup" method in the class using the bean and let Spring dynamically implement it. Instead of a direct "new aTypeImpl()", I call this method and get my bean.

    However, according to the documentation I found, I have to provide a lookup method in each class which uses the bean. I hate code duplication, but there are a couple of classes which need to instantiate my bean dynamically (again, I thought of the Factory pattern, but Spring already has/is one, so why implement another Factory of my own?).

    Note I do not want to inject static collections given in the config file - this is pretty much clear to me. My topic is rather about dynamic collections.

    Any hint on what pattern to use here?

    Thanks & best regards,

    Juergen
    Last edited by georgekue; Feb 1st, 2012, 10:28 AM.

  • #2
    I think that you want to do somethin like:

    Code:
    public class TypeFactoryImp implements TypeFactory {
         
        public abstract Type makeType();
    }
    
    <bean id="typeFactory" class="TypeFactoryImpl">
    <lookup-methd name="makeType" bean="type">
    </bean>
    
    <bean id="type" class="TypeImpl" scope="prototype">
    <!-- inject dependencies -->
    </bean>
    Then inject the typeFactory bean in any bean that need to create Types.

    Of course, you can implement ApplicationContextAware and use context.getBean("type") but then you couple your code to spring.

    Use your own factory to decouple or use ApplicationContextAware interface if coupling code to spring don't is a problem.


    HTH

    Comment


    • #3
      Thanks Chelu,

      this is exactly what I was looking for.

      Best regards.

      Comment

      Working...
      X