Announcement Announcement Module
Collapse
No announcement yet.
Best way to retrieve beans instances from the ioc container Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Best way to retrieve beans instances from the ioc container

    Hi,

    I am pretty new to Spring and I am trying to find my way in this.

    In EJB in order to get stateless beans ref from anywhere in your project(from different classes) you could use jndi lookup or annotation injection.

    How does it work with Spring?

    should I use this code in each class which desire to get reference to a certain bean:

    HTML Code:
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    MyBean myBean= (MyBean ) context.getBean("MyBean");
    Or should I declare ApplicationContext in a Singleton class and then pass it's reference between the classes and then use context.getBean(..)

    ?


    thanks,
    ray.

  • #2
    should I use this code in each class which desire to get reference to a certain bean:
    If you want to run out of memory, have a degrading performance then that is indeed the way to go. NEVER NEVER NEVER use that code to get a reference to a bean. If you use it it should be used ONCE and ONCE only to bootstrap your application.

    You shouldn't do lookups at all that is why we have dependency injection you give the object the dependencies it needs you don't go hunting around for the beans you need.

    Comment


    • #3
      Hi,
      So how will you get reference to those beans in different classes?

      If For example we have a bean called "MyBean" and I need to use it in two classes: Class A and class B. how would you get a reference to that bean in those classes? Should I pass ApplicationContext between the classes? or should I just pass the beans references?

      For example we have a Managerbean which let's say need to do some operation.

      now that operation's strategy is located in other bean(StrategyBean). so I need to pass StrategyBean ref to that Managerbean? Cant I get instance of StrategyBean from the container into Managerbean without passing it straightforward?(exactly like lookup in the ejb-world)

      thanks.
      Last edited by ray.frid; Jun 28th, 2012, 07:59 AM.

      Comment


      • #4
        You don't want to do lookups, that makes your code brittle and hard to test. You should pass the dependency to the class. YOu shouldn't pass anything around as the beans should be configured before hand and the only things you should pass around are your domain objects or value classes not your services, daos or other supporting classes, those should be injected.

        Comment

        Working...
        X