1. What is Spring?
Spring is a lightweight Inversion of Control (IoC) and Aspect-Oriented (AOP) container framework
2. How to obtain the beans configured by Spring in the program?
Method 1: Save the ApplicationContext object during initialization
Code:
Copy the code code as follows:
ApplicationContext ac = new FileSystemXmlApplicationContex("applicationContext.xml");
ac.getBean("beanId");
Note: This method is suitable for independent applications that use the Spring framework and require the program to manually initialize Spring through the configuration file.
Method 2: Obtain the ApplicationContext object through the tool class provided by Spring
Code:
Copy the code code as follows:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils
.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils
.getWebApplicationContext(ServletContext sc)
ac1.getBean("beanId");
ac2.getBean("beanId");
Method 3: Inherited from the abstract class ApplicationObjectSupport
Note: The abstract class ApplicationObjectSupport provides the getApplicationContext() method, which can easily obtain the ApplicationContext. When Spring is initialized, the ApplicationContext object will be injected through the setApplicationContext(ApplicationContext context) method of the abstract class.
Method 4: Inherited from abstract class WebApplicationObjectSupport
Note: Similar to method three, call getWebApplicationContext() to obtain WebApplicationContext
Method five: Implement the interface ApplicationContextAware
Description: Implement the setApplicationContext(ApplicationContext context) method of this interface and save the ApplicationContext object. When Spring is initialized, the ApplicationContext object will be injected through this method.