Results 1 to 3 of 3

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

  1. #1
    Join Date
    Jul 2009
    Posts
    16

    Default 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.

    Regards.

  2. #2
    Join Date
    Jul 2009
    Posts
    16

    Default

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

    Code:
     RuleMonthlyRangeBinder lRuleMonthlyRangeBinder = beanFactory
    					.getBean( RuleMonthlyRangeBinder.class );
    OK.

  3. #3
    Join Date
    Nov 2005
    Posts
    113

    Default

    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:

    Code:
    @Service
    public class MyClassImpl implements MyClass {
        private RuleMonthlyRangeBinder binder;
    
        @Autowired
        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

Posting Permissions

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