This article is based on the summary review of JavaGuide
SpringIOC/AOP
-
- What is Spring IOC?
- Spring IOC initialization process
- What is Bean
- What is AOP, the role and realization of AOP
- The difference between Spring AOP and AspcetJ AOP
- Scope of Spring Bean
- Thread Safety of Spring Singleton Bean
- What is the difference between @Component and @Bean?
- Bean life cycle
- What is SpringMVC?
- SpringMVC execution process
- Design patterns used in Spring
- How to manage transactions in Spring
- Transaction isolation level in Spring
- Transaction propagation in Spring
- @Transactional(rollbackFor = Exception.class) annotation understand?
- What is JPA?
- Use JPA to non-persistent a field in the database
What is Spring IOC?
IOC inversion of control is actually the realization of the idea of dependency inversion in the design pattern, which transfers the control of manually created objects in the program to the Spring framework to manage.
Dependency injection : pass the bottom class as a parameter to the upper class to realize the "control" of the upper class to the lower class.
Picture from source: Internet
Spring IOC initialization process
(1) First ClassPathXmlApplicationContext
obtain the provided resource file path and process it into a configuration file array
(2) Call the Refresh
method to rebuild the container. Refresh
The original will be Applicationontext
destroyed.
(3) In the Refresh
method:
- First, make preparations before creating the Bean container and call the
prepareRefrash()
method . Record the startup time and verify the xml file. - Create the Bean container, load and register the Bean , using the **
obtainFreshBeanFactory()
method. In this method would be初始化BeanFactory
,加载Bean
,注册Bean
** and so on. But itBean实例
has not been created here .
ApplicationContext
Inherited fromBeanFactory
,但是它不应该被理解为 BeanFactory 的实现类
,而是说其内部持有一个实例化的
BeanFactoryDefaultListableBeanFactory
( ). All subsequent BeanFactory-related operations are actually delegated to thisDefaultListableBeanFactory
instance for processing.
What is Bean
From the code level, it is BeanDefinition
an instance of the interface .
What is AOP, the role and realization of AOP
AOP is the meaning of aspect-oriented programming, which can encapsulate the logic and responsibilities that are not related to the business but are called by the business modules. (Such as: transaction processing, log management, permission control, etc.). It is convenient to reduce code duplication and reduce the coupling degree of modules, which is beneficial to scalability and maintainability.
SpringAOP is based on dynamic proxy.
- If an interface is implemented, SpringAOP uses JDK Proxy to create proxy objects.
- If there is no object that implements the interface, use Cglib to produce a subclass of the proxy object as a proxy.
- You can also use AspectJ. AspectJ should be considered the most complete AOP framework in the Java ecosystem
The difference between Spring AOP and AspcetJ AOP
- Spring AOP is run-time enhancement, while AspectJ is compile-time enhancement.
- Spring AOP is based on proxy, while AspectJ is based on bytecode manipulation.
- AspectJ is integrated in Spring AOP. AspectJ is recommended when there are many aspects.
Scope of Spring Bean
- singleton: the only bean instance, beans in Spring are singletons by default.
- prototype: Each request will create a new bean instance.
- request: Every HTTP request will generate a new bean, which is only valid in the current HTTP request.
- session: Each HTTP request will generate a new bean, which is only valid in the current HTTP session.
- global-session: Global session scope, only meaningful in portlet-based web applications, Spring5 has gone.
Thread Safety of Spring Singleton Bean
Singleton beans have thread safety issues. When multiple threads manipulate the non-static member variables of the same object, thread safety issues arise.
Solution: Use ThreadLocal to define member variables.
What is the difference between @Component and @Bean?
- The object is different: @Component acts on the class, and @Bean acts on the method.
- @Component combined with @ComponentScan can easily assemble classes into the Bean container.
- The @Bean annotation usually means that we define an instance of this bean in the method marked with the annotation. @Bean told Spring that this is an example of a certain class and return it to me when I need it.
- When importing third-party plug-ins or libraries, you need to use @Bean to load Spring container management, which cannot be achieved with @component.
Bean life cycle
What is SpringMVC?
MVC is a design pattern, and Spring MVC is the application of MVC pattern by Spring framework. SpringMVC is mainly used to help us with web development. In the MVC mode, the back-end is divided into Service layer to process business, Dao layer database operation, Entity layer entity class, Controller layer, and return data to the front desk.
SpringMVC execution process
- The client sends a request to
DispatcherServlet
- DispatcherServlet is called according to the request information
HandlerMapping
and resolves the corresponding requestHandler
. - After parsing the corresponding Handler (Controller controller), H
andlerAdapter
and the adapter begin to process. - HandlerAdapter calls the
真正的处理器
processing request according to the Handler , and the corresponding logical business. - After the processor finishes processing, it returns one
ModelandView对象
, Model returns a data object, and View is a logical View. Not really showing the view ViewResolver
Find the actual View based on the returned View.- DispaterServlet passes the returned Model to the View view for rendering
- Return View to the client
Design patterns used in Spring
工厂模式:
Spring uses the factory pattern to create bean objects through BeanFactory or ApplicationContext.
BeanFactory: Delayed injection, it will only be created when a bean is used.
ApplicationContext: When the container starts, all beans are created at once
单例模式
:
The default scope of Bean in Spring is singleton.
: Bean scopes as well as
ways to achieve Singleton pattern Spring :
single-case model by ConcurrentHashMap implementation singleton registry.
// Implement singleton registry through ConcurrentHashMap (thread safety)
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
// 检查缓存中是否存在实例
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//...省略了很多代码
try {
singletonObject = singletonFactory.getObject();
}
//...省略了很多代码
// 如果实例对象在不存在,我们注册到单例注册表中。
addSingleton(beanName, singletonObject);
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
//将对象添加到单例注册表
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
}
}
}
代理模式
SpringAOP is based on the proxy model.
If the proxy object implements an interface, use JDK Proxy to create the proxy object.
If the proxy object does not implement a certain interface, it will use Cglib to generate an instance of the proxy object for proxy.
The proxy in Spring can also use AspectJ, and Spring integrates AspectJ. It can be used when there are many slices.
模板方法
: Is a behavioral design pattern, which defines the skeleton of an algorithm in operation, and delays some steps to subclasses.
The use of template methods in Spring is mainly reflected in database operation classes ending in Template, such as JDBCTemplate, HiberbateTemplate.
However, Spring has improved the template method mode. Generally, template methods use subclasses to implement an operation. In Spring, the Callback mode (callback mode) is used in conjunction with the template method.
Callback mode (callback mode): Expose a certain function in the workflow to external users according to the agreed interface, provide data for external users, or require external users to provide data.
观察者模式
: Is an object behavior model. It represents a dependency between an object and an object. When an object changes, the objects that the object depends on will also react.
The event-driven model in Spring is used for this design pattern.
Spring event execution process is as follows:
(1) defines an event: a realization继承自 ApplicationEvent
, and write the corresponding constructor;
(2) defines an event listener: solid现 ApplicationListener 接口
, ;重写 onApplicationEvent() 方法
(3)
using the event publishers publish messages: throughApplicationEventPublisher 的 publishEvent() 方法发布消息
.
适配器模式
: Adapter Pattern (Adapter Pattern) converts an interface into another interface that the customer wants. The adapter pattern enables classes that are incompatible with the interface to work together, and its alias is Wrapper.
SpringAOP enhancements or notifications all use the adapter pattern, the related interface: AdvisorAdapter.
The notifications predefined by Spring should be adapted to objects of the MethodInterceptor interface (method interceptor) type through the corresponding adapter (for example, MethodBeforeAdviceInterceptor is responsible for adapting MethodBeforeAdvice).
SpringMVC中的适配器模式:
DispatcherServlet calls HandlerMapping according to the request information, and parses the Handler corresponding to the request. After parsing to the corresponding Handler (that is, the Controller controller we usually say), it starts to be processed by the HandlerAdapter adapter.
-
装饰者模式(包装器模式)
: Dynamically add some additional properties or behaviors to the object
. When the DataSource is configured in Spring, the DataSource may be a different database and data source. At this time, we will use the decorator mode (I don't understand the specific principles too much at this point). The wrapper pattern used in Spring contains Wrapper or Decorator in the class name. These classes basically add additional responsibilities to an object dynamically.
- Design patterns used in Spring:
- In Spring IOC, Spring creates bean objects in beanFactory and ApplicationContext through the factory pattern.
- Proxy mode: SpringAOP is based on the proxy mode.
- Adapter mode: The addition or notification of Spring AOP uses the adapter mode. The adapter pattern is also used in SpringMVC. (HandlerAdapter)
- Observer mode: Spring's event model uses the observer mode
- Wrapper pattern: DataSource in Spring uses the wrapper pattern to dynamically add responsibilities to the class.
- Template method pattern: All those ending with template in Spring use the template method pattern. Such as JDBCTemplate
How to manage transactions in Spring
- Programmatic transactions, hard-coded in the code.
- Declarative transactions, configured in the configuration file. Recommended usage.
Declarative transactions are divided into:
XML
annotations
Transaction isolation level in Spring
- Five constants representing isolation levels are defined in the TransactionDefinition interface:
TransactionDefinition.ISOLATION_DEFAULT: Use the default isolation level of the back-end database, the default REPEATABLE_READ isolation level used by Mysql, the default READ_COMMITTED isolation level used by Oracle.
TransactionDefinition.ISOLATION_READ_UNCOMMITTED: The lowest isolation level, allowing to read uncommitted data changes, which may lead to dirty reads, phantom reads or non-repeatable reads
TransactionDefinition.ISOLATION_READ_COMMITTED: Allows to read data that has been committed by concurrent transactions, which can prevent dirty reads, but phantom reads or non-repeatable reads may still occur
TransactionDefinition.ISOLATION_REPEATABLE_READ: The results of multiple reads of the same field are consistent, unless the data is modified by the transaction itself, which can prevent dirty and non-repeatable reads, but phantom reads may still occur.
TransactionDefinition.ISOLATION_SERIALIZABLE: The highest isolation level, fully compliant with the ACID isolation level. All transactions are executed one by one, so that there is no interference between transactions, that is, this level can prevent dirty reads, non-repeatable reads, and phantom reads. But this will seriously affect the performance of the program. Normally, this level is not used either.
Transaction propagation in Spring
- Support current affairs:
TransactionDefinition.PROPAGATION_REQUIRED (propagation required) : If there is a transaction currently, join the transaction; if there is no transaction currently, create a new transaction.
TransactionDefinition.PROPAGATION_SUPPORTS(propagation supports) : If there is a transaction currently, join the transaction; if there is no transaction currently, continue to run in a non-transactional manner.
TransactionDefinition.PROPAGATION_MANDATORY(propagation mandatory) : If there is currently a transaction, then join the transaction; if there is no current transaction, an exception will be thrown. (Mandatory: mandatory)
- Does not support current transaction
TransactionDefinition.PROPAGATION_REQUIRES_NEW : Create a new transaction, if there is a transaction currently, then suspend the current transaction.
TransactionDefinition.PROPAGATION_NOT_SUPPORTED : Run in non-transactional mode. If there is a transaction currently, the current transaction is suspended.
TransactionDefinition.PROPAGATION_NEVER : Run in non-transactional mode, if there is a transaction currently, an exception will be thrown.
- Other cases:
TransactionDefinition.PROPAGATION_NESTED: If there is currently a transaction, create a transaction to run as a nested transaction of the current transaction; if there is no current transaction, the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED. Create a new transaction
@Transactional(rollbackFor = Exception.class) annotation understand?
When the @Transactional annotation is applied to a class, all public methods of the class will have this type of transaction attribute. At the same time, we can also use this annotation at the method level to override the class-level definition. If this annotation is added to the class or method, the method in this class throws an exception, it will be rolled back, and the data in the database will also be rolled back.
If the rollbackFor attribute is not configured in the @Transactional annotation, then things will only roll back when they encounter RuntimeException, and rollbackFor=Exception.class can make things roll back when they encounter non-runtime exceptions.
What is JPA?
JPA (java persistence API) is used to manage persistence in JavaEE and JavaSE environments, and the Java API for object/relational mapping
is an interface for processing data persistence, and the specification
- The entity (pojo) represents a table in a relational database
- Each entity instance corresponds to a row in the table
- The class must be annotated with javax.persistence.Entity. The
class must contain a public or protected parameterless constructor- When an entity instance is used as a value to be passed as a separate object (for example, through the remote business interface of a session bean), the class must implement the Serializable interface
- Unique object identifier, simple primary key (javax.persistence.Id), composite primary key (javax.persistence.EmbeddledId and javax.persistence.IdClass)
Use JPA to non-persistent a field in the database
- Change static modification static
- Change to final modification
- transient modification
- @Transient annotation modification