Understand the life cycle and scope of Spring beans in a simple way
# # # introduction
Into Java learning and progress, we do it together
In our Java development, Java is the undisputed dominant development language. Can't do without those awesome open source J2EE application frameworks. Spring, for example, is an open source framework that we Java developers must know. Because it can be integrated with countless and diverse frameworks, because of its powerful IOC, AOP, and MVC.Copy the code
####1. What is a Bean in Spring? In practice, Spring provides us with an IOC container for managing our beans. Official explanation: In Spring, the objects that make up the backbone of your application and are managed by the Spring IOC container are called beans. A Bean is an object instantiated, assembled, and managed by the Spring IOC container.
2. IOC container in Spring.
IOC: Inversion of control. When the program runs, the dependent object is dynamically generated and injected into the dependent object by the [auxiliary program], and the use relationship between the two is dynamically bound.
The Spring IoC container is one such helper that takes care of object generation and dependency injection, leaving it to us to use later.
In a nutshell: IoC is the process by which an object defines its dependencies without creating them.
3. How to define a Bean
1. Use the @Component, @service, @repository, and @Controller stereotypes
For example:
@ Component
class MySpringBean {}Copy the code
Classes with these annotations are managed by Spring. The difference is that @Component, like the one in our configuration file, is used to inject our classes into Spring and let Spring manage them.
And @service, @Controller, @Repository = @Component + some specific functionality.
These annotations are often used for hierarchical operations:
With these layers, the code is loosely coupled and the calls between the codes are clear and easy to manage. Imagine how hard it would be to extend and maintain the @Controller annotation if all the request forwarding, business processing, and database manipulation code were all in one place.
The @repository annotation in the persistence layer translates native exceptions thrown by database operations into Spring’s persistence layer exceptions.
@Controller is a spring-MVC annotation that can forward and redirect requests.
@service is a business logic layer annotation that simply notes that the class is in the business logic layer.
4. The life cycle of Spring Beans
The general process is as follows:
Instantiate — Attribute assignment — initialize method — use — Destroy
Spring instantiates the bean
Spring injects values and bean references into bean properties
3. Spring passes the bean ID to setBeanName() if the bean implements the BeanNameAware interface.
4. If the bean implements the BeanFactoryAware interface, Spring calls setBeanFactory(), passing in the BeanFactory container instance
5. If the bean implements the ApplicationContextAware interface, Spring calls setApplicationContext(), passing in a reference to the bean’s application context
Come in
6, if the bean implements the BeanPostProcessor interface, the Spring will invoke them postProcessBeforeInitialization ()
Spring calls afterPropertiesSet() for beans that implement the InitializingBean interface. Similarly, if the bean uses init-method sound
Understand the initialization method, which will also be called
8, if the bean implements the BeanPostProcessor interface, the Spring will invoke them postProcessAfterInitialization ()
9. At this point, the beans are ready to be used by the application, and they will reside in the application context until the application context is destroyed
10. If the bean implements the DisposableBean interface, Spring will call its destroy() interface method. Similarly, if the bean is declared using destroy-method
Destroys the method, which is also called
5. Scope of Spring Beans
Scope limits the scope of Spring beans, which can be flexibly defined by declaring the Scope configuration item when defining beans in the Spring configuration file. For example, if you want the Bean returned by the IOC container to be the same instance every time, you can set scope to Singleton; Set scope to Prototype when you want the Bean instance returned by the IOC container to be a new instance
The Scope configuration item has five properties that describe different scopes.
(1) the singleton
When defining beans using this property, the IOC container creates only one Bean instance, and the IOC container returns the same Bean instance each time.
(2) the prototype
When defining beans using this property, the IOC container can create multiple Bean instances, returning a new instance each time.
(3) request
This property only applies to HTTP requests, and when you define a Bean with this property, a new Bean is created for each HTTP request and applies to the WebApplicationContext environment.
(4) session
This property is only used for HTTP sessions, and the same Session shares a Bean instance. Different sessions use different instances.
(5) global – the session
This property applies only to HTTP sessions, and unlike the Session scope, all sessions share a Bean instance.
The singleton and Prototype scopes will be introduced here, and the other three scopes will be included in subsequent articles
5.1 Singleton scope
Singleton is the default scope. When defining a Bean, the scope of the Bean is default to Singleton if no scope configuration item is specified. Singleton is a singleton pattern, with only one Bean instance in the overall system context. That is, you get the same instance through Spring IOC throughout the system context.
5.2 the prototype scope
Each time a Bean is called from the container, a new instance is returned, i.e. newXxxBean() is executed each time getBean() is called
5.3 Request Scope
Each HTTP request creates a new Bean, which is scoped only for the WebApplicationContext environment
5.4 Session Scope
The same HTTP Session shares a Bean. Different sessions use different beans. This applies only to WebApplicationContext
5.5 Global-session scope
This application domain applies only to WebApplicationContext
With little Lucas to learn things, must be less must be examples, below we will write a code, to see the specific difference between these scopes: first prepare a class
Public class Category {// attribute private String name; Public void setName(String name){this.name=name; Public void getName(){system.out.println (name); }}Copy the code
Singleton scope:
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <! < class=" c" class="Category" scope="singleton"> </bean> </beans>Copy the code
Public class TestSpring {public static void main(String[] args) {//Spring API ApplicationContext. Applicationcontext. XML is the self-created configuration file applicationContext Context =new ClassPathXmlApplicationContext("applicationContext.xml"); //c is the configuration file id Category =(Category)context.getBean("c"); // Instead of setting it in the configuration file, use the set method to set the property's value category.setname (" first set "); category.getName(); Categorycategory1 =(Category)context.getBean("c"); // CategoryCategory1 =(Category)context.getBean("c"); Category1.getname (); // Category1.getName (); }}Copy the code
The test class
Public class TestSpring {public static void main(String[] args) {//Spring API ApplicationContext. Applicationcontext. XML is the self-created configuration file applicationContext Context =new ClassPathXmlApplicationContext("applicationContext.xml"); //c is the configuration file id Category =(Category)context.getBean("c"); // Instead of setting it in the configuration file, use the set method to set the property's value category.setname (" first set "); category.getName(); Categorycategory1 =(Category)context.getBean("c"); // CategoryCategory1 =(Category)context.getBean("c"); Category1.getname (); // Category1.getName (); }}Copy the code
If the bean with id c is set for the first time, the bean with id C is set for the first time and the bean with id C is set for the first time. Prototype scope: Change the scope in the configuration file to prototype. All other code remains the same, including the final output of the test class: setting null the first time means that the container returns a new instance each time it calls getBean, so the first setting does not apply to the second object.Copy the code