How do I get the beans configured in Spring from parsing Java

  • 2020-04-01 02:05:09
  • OfStack

What is Spring?
Spring is a lightweight inversion of control (IoC) and aspect-oriented (AOP) container framework

How do I get the spring-configured beans in my program?
Method 1: save the ApplicationContext object on initialization
Code:


ApplicationContext ac = new FileSystemXmlApplicationContex("applicationContext.xml");
    ac.getBean("beanId");

Note: this approach is suitable for stand-alone applications that use the Spring framework and require the program to manually initialize Spring through a configuration file.

Method 2: get the ApplicationContext object through the tool class provided by Spring
Code:


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
Abstract class ApplicationObjectSupport provides getApplicationContext() method, you can easily get to ApplicationContext. When Spring initializes, the ApplicationContext object is injected through the setApplicationContext(ApplicationContext) method of the abstract class.

Method 4: WebApplicationObjectSupport inherited from the abstract class
Note: similar to method three, call getWebApplicationContext() to get the WebApplicationContext

Method 5: implement interface ApplicationContextAware
Implement the setApplicationContext(ApplicationContext context) method of the interface, and save the ApplicationContext object. When Spring initializes, the ApplicationContext object is injected using this method.


Related articles: