Results 1 to 2 of 2

Thread: Instantiation of objects with dependencies as needed

  1. #1
    Join Date
    Jan 2010
    Posts
    1

    Default Instantiation of objects with dependencies as needed

    I'm trying to use spring to instantiate an object with dependencies as the need arises (based on certain runtime conditions).

    something along the lines of

    getEvent()
    {
    if event is of type A
    instantiate AHandler using spring
    else
    instantiate BHandler using spring
    }

    Is there a better option than having my class implement ApplicationContextAware?

    -Jeff

  2. #2
    Join Date
    Jan 2010
    Posts
    9

    Default Inject a handler map instead

    From what it looks like, you are trying to use a handler to deal with some event. Unfortunately, there really is no way to 'lazy' initialize a dependency in this manner without being context aware. You can refer to the reference manual to see exactly how Spring does support lazy initialization (Section 3.3.4 for version 2.5.6, and section 3.3.3 - topic 4 for version 3.0.0).

    The best way you can achieve this is to build an event handler map in the Spring configuration, and inject this map into your bean. Depending on the type of event, you will look up the respective handler in the map. Just a simple map will do the trick, no need for anything special:

    Code:
    <bean
        id="yourBean"
        class="what.ever">
        <property name="handlerMap">
            <map>
                <entry key="eventCode1" value-ref="handler1" />
                <entry key="eventCode1" value-ref="handler2" />
                ....
            </map>
        </property>
    </bean>
    
    <bean
        id="handler1"
        class="what.ever.Handler" />
    
    <bean
        id="handler2"
        class="what.ever.Handler" />
    
    ...
    You can read more about 'collection' injection in the reference manuals (section 3.3.2.4 for version 2.5.6, and section 3.4 'Dependencies and configuration in detail' > 'Collections' for version 3.0.0).

    And as a reminder about performance tuning,
    We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. - Donald E. Knuth
    For more details on premature optimization, I refer you to Joshua Bloch's Effective Java 2nd Edition Item 55 "Optimize judiciously" (Effective Java 2nd Edition).

    Give this technique a try, and let me know if it works for you!

    - SLKF

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •