pierre tautou
pierre tautou

Reputation: 817

Spring application context

Is there any other way in J6SE to get spring (spring 3.0) application context than implement ApplicationContextAware interface?

Sorry I must improve my question. I have running application context in my J6SE app and in some classes I need it.

Upvotes: 2

Views: 2647

Answers (4)

jbabuscio
jbabuscio

Reputation: 96

After reading your question, I know you're looking for an alternative to ApplicationContextAware but I read it that you have a goal of many classes using the ApplicationContext but want to avoid implementing the interface for all these classes. This approach still uses the ApplicationContextAware but encapsulates it into a single class for reuses.

I typically load the configuration at application start up via a ContextLoaderListener in the web.xml. After this occurs, I set "MyApplicationContext" as the contextApplicationContextProvider.

<bean id="contextApplicationContextProvider" class="pkg.MyApplicationContext"></bean> 

The class must implement ApplicationContextAware as you already suggested:

public class MyApplicationContext implements ApplicationContextAware {

    private static ApplicationContext appContext;

    /* (non-Javadoc)
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext globalAppContext)
        throws BeansException {

        this.appContext = globalAppContext;

    }

    public static ApplicationContext getApplicationContext() {
        return appContext;
    }

}

The key here is that you now have a static reference to the single instance of the ApplicationContext object. Retrieving it is simple by using the static method call MyApplicationContext.getApplicationContext() for any class, spring-managed or not.

Upvotes: 2

Bozho
Bozho

Reputation: 597016

@Inject
private ApplicationContext ctx;

(or @Autowired instead of @Inject). This is the annotation replacement of ApplicationContextAware. This of course mean that the objects needs to be a spring bean.

Upvotes: 0

Rostislav Matl
Rostislav Matl

Reputation: 4543

new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE);

Upvotes: 0

duffymo
duffymo

Reputation: 308733

You can load it from the CLASSPATH.

Upvotes: 0

Related Questions