简体   繁体   中英

How can get beans if spring context.xml load from web.xml?

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/context/*-context.xml

        classpath:/context/database-context.xml
        classpath:/context/database-service-context.xml
        classpath:/context/business-process-management-service-context.xml

        classpath:/context/xml-sql-service-context.xml
        classpath:/context/ldap-service-context.xml
        classpath:/context/mail-service-context.xml
    </param-value>
</context-param>

I configured all the above beans in web.xml now I am confuse, how will get that all those beans. Do I have to do this each time ...

WebApplicationContext ctx =   WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletCo ntext());
SomeBean1 someBean1 = (SomeBean1) ctx.getBean("someBean1");
SomeBean2 someBean2 = (SomeBean2) ctx.getBean("someBean2");
.................

or is there any other way ..... please help

You can create new class that implements ApplicationContextAware like below:

public class ApplicationContextProvider implements ApplicationContextAware{

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac)
            throws BeansException {
        context = ac;
    }
}

Now you don't need to load the context each time , for getting any bean just call

ApplicationContextProvider.getApplicationContext().getBean("beanName");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM