Announcement Announcement Module
No announcement yet.
Spring IoC : How to grab an object Sub graph ? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring IoC : How to grab an object Sub graph ?

    Hi everyone,

    I'am coding with Spring 3.x with annotations.
    I put on my bean the annotation @Component.
    Inside this bean there are some members annotated with @Resource.
    In a service class, annotated with @Service, in a method of this class, I do a loop to create several instances of the bean class. If I do a "new" instruction, I won't have the whole sub graph (the bean being the root node), so my question is : how to do in my loop to "instantiate" (or wire) all the sub graph for each "instance" (I only know WebApplicationContext.getBean(...)) until here but I don't know if it still is the fashion way to do for Spring 3.x with annotation.


  • #2
    So, I just need to implements BeanFactoryAware and own a member of type BeanFactory.
    Then I get the sub graph with

     RuleMonthlyRangeBinder lRuleMonthlyRangeBinder = beanFactory
    					.getBean( RuleMonthlyRangeBinder.class );


    • #3
      It's a little hard to tell from your description, but it SOUNDS like you're not quite using Spring correctly here.

      See, Spring works best when it works using an injection philosophy, not when you're explicitly looking up the beans in the Context/BeanFactory. If your object is managed by Spring, you can just as easily inject it's dependencies using autowiring:

      public class MyClassImpl implements MyClass {
          private RuleMonthlyRangeBinder binder;
          public MyClassImpl(RuleMonthlyRangeBinder binder) {
              this.binder = binder;
      If you need to get ALL implementations of an interface, just autowire a collection of the interface. That'll automatically pull everything in.

      As a rule of thumb, I consider use of getBean() in "normal" code to be a red flag - if you're using it, there's a pretty good chance you're using the framework incorrectly.

      Hope this helps
      - Don