This article provides a detailed analysis of how to obtain the bean configured in Spring in Java. For more information, see
1. What is Spring?
Spring is a lightweight container framework for IoC and AOP.
2. How can I obtain Spring-configured beans in a program?
Method 1: Save the ApplicationContext object during initialization
Code:
Copy codeThe Code is as follows:
ApplicationContext ac = new FileSystemXmlApplicationContex ("applicationContext. xml ");
Ac. getBean ("beanId ");
Note: This method is applicable to standalone applications using the Spring framework. You need to manually initialize Spring through the configuration file.
Method 2: Obtain the ApplicationContext object through the tool class provided by Spring.
Code:
Copy codeThe Code is 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: inherit from the abstract class ApplicationObjectSupport
Description: The abstract class ApplicationObjectSupport provides the getApplicationContext () method to conveniently obtain ApplicationContext. During Spring initialization, The ApplicationContext object is injected through the setApplicationContext (ApplicationContext context) method of this abstract class.
Method 4: inherit from the abstract class WebApplicationObjectSupport
Note: method 3 is similar. Call getWebApplicationContext () to obtain WebApplicationContext.
Method 5: implement the ApplicationContextAware Interface
Note: implement the setApplicationContext (ApplicationContext context) method of this interface and save the ApplicationContext object. During Spring initialization, The ApplicationContext object is injected using this method.