Spring gets ApplicationContext

Source: Internet
Author: User

In Spring+struts+hibernate, it is sometimes necessary to use the spring context. When the project starts, the context is automatically initialized based on the ApplicationContext configuration file, and you can use the Applicationcontextaware interface to get the spring context. Create the following class:

 PackageCom.school.tool;Importorg.springframework.beans.BeansException;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.ApplicationContextAware;Importorg.springframework.stereotype.Component; @Component Public classSpringcontextutilImplementsApplicationcontextaware {Private StaticApplicationContext ApplicationContext;  Public voidSetapplicationcontext (ApplicationContext ApplicationContext)throwsbeansexception {springcontextutil.applicationcontext=ApplicationContext; }     Public StaticApplicationContext Getapplicationcontext () {returnApplicationContext; } @SuppressWarnings ("Unchecked")     Public Static<T> T Getbean (String name)throwsbeansexception {return(T) Applicationcontext.getbean (name); }}

Configure this class in the ApplicationContext configuration file:

<id= "Springcontextutil"  class= " Com.school.tool.SpringContextUtil "/>

This will automatically call the Setapplicationcontext () method to obtain the ApplicationContext when the context is initialized according to ApplicationContext.

You can also use

Classpathxmlapplicationcontext ("Applicationcontext.xml")

To get ApplicationContext, but this is equivalent to the re-initialization of the context, the speed is very slow, and the grid is not high, it is not recommended.

Spring gets ApplicationContext

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.