Spring obtains ApplicationContext and applicationcontext.

Source: Internet
Author: User

Spring obtains ApplicationContext and applicationcontext.

In Spring + Struts + Hibernate, Spring context is sometimes used. When the project is started, the context is automatically initialized Based on the applicationContext configuration file. You can use the ApplicationContextAware interface to obtain the Spring context. Create the following classes:

package com.school.tool;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class SpringContextUtil implements ApplicationContextAware {    private static ApplicationContext applicationContext;    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        SpringContextUtil.applicationContext = applicationContext;    }    public static ApplicationContext getApplicationContext() {        return applicationContext;    }    @SuppressWarnings("unchecked")    public static <T> T getBean(String name) throws BeansException {        return (T) applicationContext.getBean(name);    }}

Configure this class in the applicationContext configuration file:

<bean id="springContextUtil" class="com.school.tool.SpringContextUtil" />

In this way, when the context is initialized Based on applicationContext, The setApplicationContext () method is automatically called to obtain ApplicationContext.

You can also use

ClassPathXmlApplicationContext("applicationContext.xml")

Obtain ApplicationContext. However, this is equivalent to re-initializing the context. The speed is very slow and the Force Grid is not high. It is not recommended.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.