Chinthaka Dharmasiri
Chinthaka Dharmasiri

Reputation: 780

new ClassPathXmlApplicationContext() creating new set of beans

Does loading the application context in the following manner mean creating another context apart from the context created by a ContextLoader?

I require the application context to be loaded for a non-bean class.

private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "channel-integration-context.xml");

It seems that it creates another bean context according to my observation. If so what is a better workaround.

Please help.

Upvotes: 4

Views: 940

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Unless some very special reason, usually there's no point of creating multiple ApplicationContexts.

You can create a singleton:

public class ApplicationContextWrapper {
    private static ApplicationContext INSTANCE = null;

    private ApplicationContextWrapper() {

    }

    public static ApplicationContext getIntance() {
        if (INSTANCE == null) {
            //note you can add more Spring XML configuration filenames in this array
            String[] contexts = new String[] {"channel-integration-context.xml"};
            INSTANCE = new ClassPathApplicationContext(contexts);
        }
        return INSTANCE;
    }
}

And you can use it with:

private static ApplicationContext applicationContext = ApplicationContextWrapper.getInstance();

Upvotes: 1

Related Questions