The most common way is to use Classpathxmlapplicationcontext, Filesystemclasspathxmlapplicationcontext, Filesystemxmlapplicationcontext and other objects to load the spring configuration file, this is also possible, but when the spring configuration file is loaded, Generates a new Applicaitoncontext object instead of which one the spring container generates for us, which creates redundancy, so it doesn't take the way the application loads the file manually. Instead, use Applicationcontextaware to let the spring container automatically pass its generated applicationcontext into the specified class. The context of spring can be easily accessed in the future through this class.
Applicationcontextaware classes used in 1web engineering:
/**
* Save the spring applicationcontext with a static variable to remove the Applicaitoncontext in any code.
*
*/
public class Springcontextholder implements Applicationcontextaware {
private static ApplicationContext ApplicationContext;
/**
* Implement the context injection function of the Applicationcontextaware interface and store it in a static variable.
*/
public void Setapplicationcontext (ApplicationContext applicationcontext) {
Springcontextholder.applicationcontext =applicationcontext;
}
/**
* Gets the applicationcontext stored in the static variable.
*/
public static ApplicationContext Getapplicationcontext () {
Checkapplicationcontext ();
return applicationcontext;
}
/**
* Gets the bean from static variable ApplicationContext, automatically transforms to the type of the assigned value object.
*/
@SuppressWarnings ("Unchecked")
public static <T> T Getbean (String name) {
Checkapplicationcontext ();
Return (T) Applicationcontext.getbean (name);
}
/**
* Gets the bean from static variable ApplicationContext, automatically transforms to the type of the assigned value object.
*/
@SuppressWarnings ("Unchecked")
public static <T> T Getbean (class<t> clazz) {
Checkapplicationcontext ();
Return (T) Applicationcontext.getbeansoftype (clazz);
}
private static void Checkapplicationcontext () {
if (ApplicationContext = = null)
throw new IllegalStateException ("Applicaitoncontext not injected, please define Springcontextutil in Applicationcontext.xml");
}
You also need to define the bean in XML so that spring will not call Setapplicationcontext (ApplicationContext when it is finished creating ApplicationContext). ApplicationContext) is injected into the class, and for some static classes it is convenient to access the bean instance through Springcontextholder because it cannot be injected.
<bean id= "Springcontextholder" class= "xxxxxx. Springcontextholder "lazy-init=" false "/>
2. For Java Engineering, the meaning of Applicationcontextaware is not very large, because the normal Java project has no way to load the spring context as the Web application starts. Therefore, it is easy to create the application manually.