Announcement Announcement Module
Collapse
No announcement yet.
How to inject the right bean implementation based on some value resolved at runtime? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to inject the right bean implementation based on some value resolved at runtime?

    What I want to do is very straight forward, but I'm not sure what the right approach would be in Spring since it's sort of new to me.

    Anyway, I have a simple class hierarchy similar to the one on the attached diagram: Attachment

    Going by the diagram, what I want to do is dynamically inject an instance of the one of the concrete IWidget implementations based on some value I get from a configuration service. Using straight-up Java (w/o an IoC framework's help), I would probably do something like:

    public class MyApp {

    private IConfigServcie config;

    ...

    public void printWidget(...) {

    String widgetType = config.getProperty(someKey);
    IWidget widget = WidgetFactory.getWidget(widgetType);
    widget.drawSelf();
    }
    }


    What is the best way to do this in Spring (via DI)?

    I looked into autowiring by-name (something like what they do on http://www.tutorialspoint.com/spring...ing_byname.htm).

    However, that doesn't seem like much of an injection to me... Looks more like dependency look-up?
    Attached Files
    Last edited by jersey355; Apr 5th, 2013, 04:14 PM.

  • #2
    Try and use ProxyFactoryBean. You will get lot of examples on the net.

    Comment


    • #3
      Thanks amitfou, but I think I found a simple and more dynamic approach. Sticking with my example above, here's what I did:

      Java:


      public class MyApp {

      @Autowired
      private IConfigServcie config;

      @Autowired
      private Map<String, IWidget> widgets;

      ...

      public void printWidget(...) {

      String widgetType = config.getProperty(someKey);
      IWidget widget = widgets.get(widgetType);
      widget.drawSelf();
      }
      }


      In my XML, I just need to make sure there's a bean configured and added to my map for each potential "widgetType" as follows:


      <beans:bean id="roundWidget" class="com.acme.widgets.roundWidget" />
      <beans:bean id="squareWidget" class="com.acme.widgets.squareWidget" />
      <beans:bean id="triangleWidget" class="com.acme.widgets.triangleWidget" />

      <util:map id="widgetBuilders" map-class="java.util.HashMap">

      <beans:entry key="round"><beans:ref local="roundWidget" /></beans:entry>
      <beans:entry key="square"><beans:ref local="squareWidget" /></beans:entry>
      <beans:entry key="triangle"><beans:ref local="triangleWidget" /></beans:entry>
      </util:map>

      Comment

      Working...
      X