Spring (2) --Bean topic

Do you know about beans in Spring? What are the scopes (Scope)?

The Spring official documentation explains the bean:

In Spring, the objects that form the backbone of your application and that are managed by the Spring IOC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

Translation-  >

In Spring, the objects that form the backbone of the application and are managed by the Spring IOC container (ApplicationContext) are called beans . A bean is an object instantiated, assembled and managed by the Spring IOC container.

Key information-  >

(1) bean is an object, one or more, unlimited number;

(2) The bean is managed by a container called IOC in Spring;

(3) The application is composed of beans;

Beans in Spring have five scopes (Scope):

(1) Singleton: There is only one Bean instance in a Spring container. This is the default configuration of Spring, and all containers share an instance.

(2) Prototype: Each call creates a new Bean instance.

(3) Request: In the Web project, create a new Bean instance for each http request.

(4) Session: In the Web project, create a new Bean instance for each http session. (5) GlobalSession: only useful in portal applications, creating a new Bean instance for each global http session.

Added: Scope describes how the Spring container creates an instance of Bean.

What are the annotations for declaring a class as Bean and the annotations for injecting beans in Spring?

Annotation declared as Bean:

(1) @Component: General annotation, any class can be marked as a spring component. If a Bean does not have a clear role, you can use @Component annotation annotation.

(2) @Service: Used at the business logic layer (service layer).

(3) @Repository: Used in the data access layer (dao layer).

(4) @Controller: used in the presentation layer (MVC-> Spring MVC), mainly used to receive user requests and call the Service layer to return data to the front-end page.

Annotation of injected Bean (generally common):

(1) @Autowired: Annotation provided by Spring.

(2) @Inject: Annotation provided by JSR-330.

(3) @Resource: Annotation provided by JSR-250.

What is the difference between @Component and @Bean?

(1) The role of the object is different: @Component acts on the class, @Bean acts on the method.

(2) @Component is usually automatically detected and automatically assembled into the Spring container through class path scanning (use the @ComponentScan annotation to define the path to be scanned from which the class that needs to be identified is automatically assembled into the spring Bean container) . The @Bean annotation is usually defined and generated in the method marked with the annotation. @Bean tells Spring that this is an instance of a certain class, and it is returned to me when I need to use it.

(3) @Bean annotations are more customizable than @Component annotations, and in many places, you can only register beans through @Bean annotations, such as classes in third-party libraries.

Are Beans in Spring thread-safe?

As an IOC / DI container, Spring helps us manage many "beans". But in fact, Spring itself does not provide a thread safety strategy. The root cause of each bean's thread safety problem is the design of each bean itself. Therefore, whether thread safety requires developers to write code to solve thread safety problems.

Stateless objects, whether single or multiple, are thread-safe. Stateless objects will naturally not destroy their own state due to the alternate scheduling of multiple threads and cause thread safety problems. Stateless objects include DO, DTO, and VO, which we often use, are anemia objects that are only solid models of data, as well as Service, DAO, and Controller. These objects do not have their own state, they are only used to perform certain operations. For example, the functions provided by each DAO are only CRUD to the database, and each database Connection is used as a local variable of the function (local variables are in the user stack, and the user stack itself is a private memory area of ​​the thread, so it does not exist Thread safety issues), close immediately after use (or return to the connection pool). Do not declare any stateful instance variables or class variables in the bean . If so, use ThreadLocal to make the variables private to the thread. If the bean instance variables or class variables need to be shared among multiple threads, then Can only use Synchronized, Lock, CAS and other methods to achieve thread synchronization.

Additional notes:

What are stateful and stateless objects?

1. Stateful means having data storage function . Stateful objects (Stateful Beans) are objects with instance variables that can hold data and are not thread-safe. No state is retained between different method calls.

2. Statelessness is an operation that cannot save data . Stateless objects (Stateless Bean) are objects that have no instance variables. They cannot store data, are invariant classes, and are thread-safe.

Bean life cycle

  For SpringBean, it is not that the bean instantiation is triggered during the startup phase. Only when the client calls the getBean () method of the BeanFactory in an explicit or implicit manner, it will trigger the instantiation method of the class . Of course, for BeanFactory, not all getBean () methods will instantiate the Bean object. For example, when the scope is singleton, it will only instantiate the Bean object for the first time, and then directly return the object. However, if you are using the ApplicationContext container, the instantiation methods of all beans registered in the container will be called immediately when the container starts.

The full version process is as follows:

Simplified translation:

1. instantiate [ɪns'tænʃɪeɪt] bean   instantiates the bean  , the Bean container finds the definition of Spring Bean in the configuration file, and uses the Java reflection mechanism to create an instance of Bean.

2. Populate properties  encapsulate properties (injected object properties) . If some property values ​​are involved, use the set () method to set some property values.

3. 执行 Aware

(1) If the bean implements the BeanNameAware interface, call the setBeanName () method and pass in the name of the bean .

(2) If the Bean implements the BeanFactoryAware interface, call the setBeanFactory () method and pass in the BeanFactory container instance ;

(3) If the Bean implements the ApplicationContextAware interface, call the setApplicationContext () method .

4. If there is a class that implements  BeanPostProcessor (pre-processing) , execute postProcessBeforeInitialization ().

5.InitializingBean, init-method inspection and execution

(1) If the Bean implements the InitializingBean interface, execute the afterPropertiesSet () method.

(2) adjusting the self-defined initialization method init-method., If the implementation of the method specified in the configuration file is defined Bean contains init-method property.

6. If there is a class that implements  BeanPostProcessor (post-processing)  , execute postProcessAfterInitialization ().

7. Bean is ready to use and execute business processing.

8. Perform the destruction method

(1) When destroying the Bean, if the Bean implements the DisposableBean interface, execute the destroy () method.

(2) Call the custom destruction method destroy-method. When the bean is to be destroyed, if the bean definition in the configuration file contains the destroy-method attribute, the specified method is executed.

Source code analysis to be added

Common interview questions?

(1) What are the scope of Spring Bean  ? How many registration methods does it have?

(2)  What is the bean with the same name? How did it come about? How should it be avoided?

(3) Bean  life cycle?

Reference / Good article

(1) Books-SpringBoot actual combat-edited by Wang Yunfei 

(2) Talk about thread safety in Spring--

https://juejin.im/post/5a0045ef5188254de169968e

(3) "Have you interviewed today"-Spring

https://juejin.im/post/5e6d993cf265da575b1bd4af

(4) Pull hook course-analysis of Java source code

https://kaiwu.lagou.com/course/courseInfo.htm?courseId=59

Guess you like

Origin www.cnblogs.com/liaowenhui/p/12750070.html