如果spring context.xml从web.xml加载,如何获取bean?

时间:2016-05-23 07:17:43

标签: java xml spring spring-mvc

<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>

我现在在web.xml中配置了所有上述bean 我很困惑,怎么会得到那些豆子。 我每次都必须这样做......

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

还是有其他方式.....请帮助

1 个答案:

答案 0 :(得分:0)

您可以创建实现ApplicationContextAware的新类,如下所示:

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;
    }
}

现在您不需要每次加载上下文,只需调用任何bean

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