Results 1 to 2 of 2

Thread: Accessing application context

  1. #1

    Default Accessing application context

    Hi,
    I would like to know how I could access the application context in a class not instantiated by spring.

    I was able to the access the application context before in classes instantiated by spring by implenting ApplicationContextAware.

    But in the current case when I tried to implement ApplicationContextAware the applicationContext is always null.

    Could anyone help me in that?

    Thanks in advance.

    Sherihan.

  2. #2
    Join Date
    Jul 2006
    Location
    Philadelphia, PA, USA
    Posts
    341

    Default Try SingletonBeanFactoryLocator

    Hi Sherihan,

    Although it is a best practice to avoid writing container-aware code, there are certain circumstances in which this is necessary. Like you said, it can be a problem when Spring cannot be used to instantiate the class. An example of this is with EJBs, because the EJB container is responsible for creating them. Spring provides EJB-specific solutions for this issue.

    I think your best bet might be to use either the SingletonBeanFactoryLocator or the ContextSingletonBeanFactoryLocator.

    Here is a short summary from the Spring documentation: Glue code and the evil singleton.

    Assuming you have a simple application with only one ApplicationContext (named "myApplicationContext.xml"), here is what I would suggest:

    1) Create a new file, beanRefFactory.xml (which is the default name):
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
     
    <beans>
       <bean id="mainApplicationContext" lazy-init="true" class="org.springframework.context.support.ClassPathXmlApplicationContext">
          <constructor-arg>
             <value>myApplicationContext.xml</value>
          </constructor-arg>
       </bean>
    </beans>
    2) In the classes that require access to the ApplicationContext, add the following code:
    Code:
    public class SomeClassWhichNeedsAppContextAccess {
    
       public static final String BEAN_FACTORY_KEY = "mainApplicationContext";
    
       public Object getBean(String beanName) {
          BeanFactoryLocator locator = SingletonBeanFactoryLocator.getInstance();
          BeanFactoryReference bfr = locator.useBeanFactory(BEAN_FACTORY_KEY);
          Object object = bfr.getFactory().getBean(beanName);
          bfr.release();
          return object;
       }
    
    }
    Now this of course assumes that the classes in question can be modified. Can you provide more details as to your exact problem?

    Hope this helps!

    -Arthur Loder

Posting Permissions

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