Spring framework
1. What is the difference between BeanFactory and ApplicationContext
BeanFactory is the bottom interface of Spring and the core of IoC, defining the basic functions of IoC.
BeanFactory has the characteristics of delayed instantiation . At startup, the bean will not be instantiated, and the bean will be instantiated only when the bean needs to be obtained from the container. (Generally used in places with small memory such as mobile devices)
ApplicationContext is a sub-interface of BeanFactory, which provides more functions than BeanFactory: internationalization, resource access, AOP and so on.
ApplicationContext will instantiate all beans when it starts, and can Lazy-init
implement delayed instantiation for bean configuration .
2. The life cycle of Spring Bean
1. Load the Bean definition
1. loadBeanDefinitions
: Record the Bean definition inbeanDefinitionMap中
registerBeanDefinition class -> registerBeanDefinition() method
Second, create a Bean object
1. Build objects
Objects are constructed one by one by traversing.
AbstractAutowireCapableBeanFactory类->createBeanInstance()
2. Fill attributes
populateBean()
3. Initialization
initializeBean()
3.1: applyBeanPostProcessorsBeforeInitialization()
: Apply Bean post-processor before initialization
3.2: invokeInitMethods()
: Initialization
3.3: applyBeanPostProcessorsAfterInitialization()
: Apply Bean post-processor after initialization
Three, use
After the initialization is complete, the Bean object can be used normally.
4. Destroy
1. Before destruction
Annotation@PreDestory
method
2. Destroy
DisposableBean->destory()
Bean->destory-method()
3. How to implement Spring IOC
IoC: Inversion of Control Inversion of Control.
Easy-to-understand understanding: We have the control ability to create objects, and the inversion is to create objects by the program, not by us to create objects.
There are many ways to implement IoC, the most common of which is DI (Dependency Injection Dependency Injection). Objects define their dependencies through construction method parameters, factory method parameters, properties set on object instances after construction or factory methods return, and dependencies are injected from outside the class (the container injects these dependencies when creating beans).
There are three ways of spring common dependency injection: 1. Construction method 2. set 3. Annotation injection @Autowired
Spring provides two IoC containers:
1、BeanFactory
2、ApplicationContext
For details, please refer to interview question 1
After understanding the life cycle of Spring Bean, we can find that the creation of Bean objects is not created manually by us, but through the underlying components of Spring. 加载->创建->销毁
This process is the process of Spring IoC.
4. Talk about Spring AOP and its implementation principle
4.1 AOP concept
AOP: Aspect Orient Programming Aspect-oriented programming.
Purpose: To realize the technology of adding additional functions without modifying the source code.
Personal understanding: the source code is a straight tree, and more species need to be seen on this tree. It is obviously time-consuming and laborious to replant next to the tree. At this time, through grafting technology, it can be achieved by grafting on the cut surface of the tree Purpose. (AOP)
4.2 AOP use
For specific usage, please refer to: https://blog.csdn.net/Cr1556648487/article/details/126777903
4.3 Principle of AOP
The bottom layer of Spring AOP adopts dynamic proxy, which supports JDK dynamic proxy and Cglib dynamic proxy.
JDK dynamic proxy can only create dynamic proxy instances for interfaces . It is necessary to obtain the interface information of the proxy class, generate a dynamic proxy class that implements the proxy interface through reflection, and then generate an instance object of the dynamic proxy class through the construction method, and use it before calling the specific method invokeHandler()
.
Since the asm package of Cglib dynamic proxy, the bytecode of the proxy class is loaded in and its subclass is generated.
5. Dynamic proxy (cglib and JDK)
JDK dynamic proxy:
The aspect logic is defined by implementing the methods InvocationHandler
of the interface invoke()
.
Conditions of Use:
- 1. Business target objects can only create proxy instances for interfaces
- 2. Interceptor implementation
InvocationHandler
- 3. By
Proxy.newProxyInstance()
generating proxy objects
Cglib dynamic proxy:
Based on ASM
the bytecode generation library, it allows modification and dynamic generation of bytecode at runtime.
The difference between JDK dynamic proxy and Cglib dynamic proxy
-
JDK dynamic proxies only proxy for interface implementation classes. That is, only for the interface .
-
Cglib implements proxies for classes, using the inheritance method.
6. Spring transaction implementation
-
programmatic transaction
Concept: Precisely define transaction boundaries in business code
Call in the code block:
beginTransaction()、commit()、rollback()
and other related methods -
declarative transaction
Helps users decouple operations from transaction rules. Simply put, programmatic transactions invade the business code, but provide more detailed transaction management; while declarative transactions are based on AOP, so they can not only play the role of transaction management, but also do not affect the specific implementation of business code.
Use:
:@EnableTransactionManagement
Enable transaction management
:@Transactional
open transaction
@Transactional
Reason for failure of transaction annotation:
- The method modifier is not
public
- Method internal call transaction
- The exception was caught within the transaction, no new exception was thrown
- The rollbackFor attribute is incorrectly configured
7. The underlying principles of Spring transactions
Use transaction steps:
- Get database connection
- open transaction
- perform data manipulation
- Commit transaction/rollback transaction
- close connection
Spring has done the operations of opening, committing and rolling back transactions in the framework, so that the business code and transaction code are decoupled. This function is realized based on AOP .
8. Custom annotation implementation function
Reference: https://www.jianshu.com/p/7c2948f64b1c
9. SpringMVC running process
Core code: DispatcherServlet.java -> doDispatch()
- user request
- DispatcherServlet Central Scheduler finds HandlerMapping to get Handler by request
- DispatcherServlet Central Scheduler finds HandlerAdapeter through Handler
- The processor adapter calls the controller written by the user and returns ModelAndView (based on JSON interaction, the returned ModelAndView is empty, and the front end can already receive the return value at this time)
- The DispatcherServlet central dispatcher finds
ModelAndView
the correspondenceViewResolver
and returnsView
- Render View
- Return the rendered View
10. SpringMVC startup process
View details: https://blog.51cto.com/u_9587581/2398187
11. Spring singleton implementation
Spring's singleton mode is implemented by using: singleton registry .
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<String, Object>(16);
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
//Spring获取单例模式方法
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
There are 3 Map collections here:singletonObjects、earlySingletonObjects、singletonFactories
The singleton acquisition order is:singletonObjects -> earlySingletonObjects -> singletonFactories
singleonObjects
: cache of singleton objectsearlySingletonObjects
: cache of singleton objects exposed in advancesingletonFactories
: the cache of the singleton object factory
12. What design patterns are used in Spring
1. Factory mode: BeanFactory, ApplicationContext
2. Singleton mode: Bean defaults to singleton mode
3. Proxy mode: AOP function uses JDK dynamic proxy and Cglib dynamic proxy
4. Adapter mode: The interceptor of Spring AOP uses the adapter mode