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