This article is a detailed analysis of how to obtain the beans in spring in Java, the need for a friend reference under
One, what is spring?
Spring is a lightweight, control reversal (IoC) and aspect-oriented (AOP) container framework
How do I get a spring-configured bean in a program?
Method One: Save the ApplicationContext object when initializing
Code:
Copy Code code as follows:
ApplicationContext ac = new Filesystemxmlapplicationcontex ("Applicationcontext.xml");
Ac.getbean ("Beanid");
Note: This approach applies to stand-alone applications that use the spring framework, and requires programs to manually initialize the spring by using a configuration file.
Method Two: Get the ApplicationContext object from the tool class provided by spring
Code:
Copy 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 Three: inherit from abstract class Applicationobjectsupport
Description: Abstract class Applicationobjectsupport provides Getapplicationcontext () method, which can be easily obtained to ApplicationContext. When spring initializes, the ApplicationContext object is injected through the Setapplicationcontext (ApplicationContext context) method of the abstract class.
Method Four: Inherit from abstract class Webapplicationobjectsupport
Description: Similar to method three, call Getwebapplicationcontext () to get Webapplicationcontext
Method Five: Implement Interface Applicationcontextaware
Description: Implements the Setapplicationcontext (ApplicationContext context) method of the interface and saves the ApplicationContext object. When spring initializes, the ApplicationContext object is injected by this method.