In Web applications, the Spring container is typically configured declaratively: Developers simply configure a Listener in web.xml that initializes the Spring container. MVC framework can call beans directly from the Spring container without accessing the Spring container itself. In this case, the beans in the container are container-managed and do not need to actively access the container, only to receive dependency injection from the container.

However, in special cases where a Bean needs to implement a function that must be implemented with the help of the Spring container, the Bean must first obtain the Spring container and then implement the function with the help of the Spring container. To have a Bean get its Spring container, you can have the Bean implement the ApplicationContextAware interface.

The following example is a utility class that implements ApplicationContextAware and can be referenced by other classes to manipulate the Spring container and its Bean instances.

public class SpringContextHolder implements ApplicationContextAware {
	private static ApplicationContext applicationContext = null;
 
	/**
	 * 获取静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		assertContextInjected();
		returnapplicationContext; } /** * The Bean from the static variable applicationContext is automatically converted to the assigned object type. */ @suppressWarnings ("unchecked")
	public static <T> T getBean(String name) {
		assertContextInjected();
		return(T) applicationContext.getBean(name); } /** * get Bean from static variable applicationContext, */ Public static <T> T getBean(Class<T> requiredType) {assertContextInjected();returnapplicationContext.getBean(requiredType); } /** * Clear SpringContextHolder ApplicationContext to Null. */ public static voidclearHolder() { applicationContext = null; } /** * implements the ApplicationContextAware interface to inject Context into static variablessetApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext;  } /** * Check that ApplicationContext is not emptyassertContextInjected() { Validate.validState(applicationContext ! = null,"ApplicaitonContext property is not injected, please define SpringContextHolder in ApplicationContext.xml."); }}Copy the code

The Spring container detects all beans in the container, and if it finds a Bean that implements the ApplicationContextAware interface, the Spring container creates the Bean, The automatic invocation of the Bean setApplicationContextAware () method, this method is invoked, The container itself is passed to the method as an argument — the implementation part of the method assigns parameters passed in by Spring (the container itself) to the applicationContext instance variable of the class object, so that the container itself can then be accessed through the applicationContext instance variable.