In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "the method of spring annotation configuration to realize transaction control and the realization mechanism of transaction". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
Spring Annotation configuration for transaction Control
1. Import related dependencies
2. Create a spring configuration class
3. Create a JdbcConfig data source configuration class
4. Create a TransactionConfig transaction configuration class
5. Create jdbcConfig.properties
6. Use transaction comments
Transaction implementation Mechanism of Spring Annotation
1. The implementation mechanism of transaction
AOP dynamic agent for method interception
Transaction manager commits or rolls back a transaction
2. Matters needing attention in the use of annotated transactions
Correctly set the propagation property of @ Transactional (familiar with the propagation characteristics of transactions)
Correctly set the rollbackFor property of @ Transactional
@ Transactional is valid only when applied to the public method
To avoid the problem of self-calling AOP of Spring, you must call across service
The problem of communication of affairs
Spring annotation configuration to achieve transaction control 1. Import related dependencies
This project uses spring's JdbcTemplate template class to simplify jdbc code in the control layer. If your project uses another persistence layer framework, you can switch.
Org.springframework spring-context 5.0.2.RELEASE org.springframework spring-jdbc 5.0.2.RELEASE org.springframework spring-tx 5.0.2.RELEASE 2. Create spring configuration class package config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration Import org.springframework.context.annotation.Import;import org.springframework.context.annotation.PropertySource;import org.springframework.transaction.annotation.EnableTransactionManagement / * * spring configuration class, equivalent to bean.xml * / @ Configuration / / declare to be configuration class @ ComponentScan ("com.gzl") / / enable spring annotation scanning @ Import ({JdbcConfig.class,TransactionConfig.class}) / / load JdbcConfig and TransactionConfig classes @ PropertySource ("jdbcConfig.properties") / / load configuration @ EnableTransactionManagement / / Open transaction annotation public class SpringConfiguration {} 3 in the properties file, create JdbcConfig data source configuration class package config Import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.datasource.DriverManagerDataSource;import javax.sql.DataSource;/** * configuration classes related to connecting to the database * / public class JdbcConfig {@ Value ("${jdbc.driver}") private String driver; @ Value ("${jdbc.url}") private String url @ Value ("${jdbc.username}") private String username; @ Value ("${jdbc.password}") private String password; / * create JdbcTemplate * @ param dataSource * @ return * / @ Bean (name= "jdbcTemplate") public JdbcTemplate createJdbcTemplate (DataSource dataSource) {return new JdbcTemplate (dataSource) } / * create data source object * @ return * / @ Bean (name= "dataSource") public DataSource createDataSource () {DriverManagerDataSource ds = new DriverManagerDataSource (); ds.setDriverClassName (driver); ds.setUrl (url); ds.setUsername (username); ds.setPassword (password); return ds;} 4, create TransactionConfig transaction configuration class package config Import org.springframework.context.annotation.Bean;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;/** * transaction-related configuration class * / public class TransactionConfig {/ * is used to create a transaction manager object * @ param dataSource * @ return * / @ Bean (name= "transactionManager") public PlatformTransactionManager createTransactionManager (DataSource dataSource) {return new DataSourceTransactionManager (dataSource) 5. Create a jdbcConfig.propertiesjdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/eesyjdbc.username=rootjdbc.password=1234
6. Use transaction comments
Add @ Transactional to the method that needs to add a transaction
Transaction implementation mechanism of Spring annotation mode 1. Transaction implementation mechanism AOP dynamic proxy for method interception
When applying a system call to the target method that declares @ Transactional, Spring Framework uses the AOP proxy by default and generates a proxy object when the code runs. Based on the property configuration information of @ Transactional, this proxy object determines whether the target method that declares @ Transactional is intercepted by the interceptor TransactionInterceptor.
During TransactionInterceptor interception, a transaction is created and joined before the target method starts execution, and the logic of the target method is executed. Finally, according to whether the execution is abnormal, the abstract transaction manager AbstractPlatformTransactionManager is used to operate the data source DataSource to commit or roll back the transaction, as shown in the following figure.
Note: the above two xxxServiceImpl represent the call to the same service. The dotted line is used to indicate that the method of the service is to be called. Before entering the method of the service, it is intercepted by aop before entering the service method (the service represented by the solid line).
There are two kinds of Spring AOP agents: CglibAopProxy and JdkDynamicAopProxy. The figure above takes CglibAopProxy as an example.
For CglibAopProxy, you need to call the intercept method of DynamicAdvisedInterceptor of its inner class.
For JdkDynamicAopProxy, you need to call its invoke method.
Transaction manager commits or rolls back a transaction
The framework of transaction management is provided by abstract transaction manager AbstractPlatformTransactionManager, while the specific underlying transaction implementation is implemented by the concrete implementation class of PlatformTransactionManager, such as transaction manager DataSourceTransactionManager.
Different transaction managers manage different data resources DataSource, such as DataSourceTransactionManager's Connection for managing JDBC.
The relationship between PlatformTransactionManager,AbstractPlatformTransactionManager and the concrete implementation class is shown in figure 2.
2. Matters needing attention in the use of annotated transactions
When you have a better understanding of the annotation-based implementation steps of Spring and the internal implementation mechanism of transactions, you will better use annotated transaction management to avoid the problem that data cannot be rolled back when the system throws an exception.
Correctly set the propagation property of @ Transactional (familiar with the propagation characteristics of transactions)
It is important to note that the following three propagation may not start a transaction. The target method was expected to manage the transaction, but if these three propagation are misconfigured, the transaction will not be rolled back.
1.TransactionDefinition.PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.
2.TransactionDefinition.PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.
3.TransactionDefinition.PROPAGATION_NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.
Correctly set the rollbackFor property of @ Transactional
By default, if an unchecked exception (an exception inherited from RuntimeException) or Error is thrown in a transaction, Spring rolls back the transaction; otherwise, Spring does not roll back the transaction.
If you throw other types of exceptions in a transaction and expect Spring to roll back the transaction, you can specify rollbackFor.
Example:
@ Transactional (propagation= Propagation.REQUIRED,rollbackFor= MyException.class)
By analyzing the Spring source code, we can see that if the exception thrown in the target method is a subclass of the exception specified by rollbackFor, the transaction will also be rolled back.
Listing 3. GetDepth method of RollbackRuleAttribute
Private int getDepth (Class exceptionClass, int depth) {if (exceptionClass.getName () .contains (this.exceptionName)) {/ / Found it! Return depth;} / / If we've gone as far as we can go and haven't found it... If (exceptionClass = = Throwable.class) {return-1;} return getDepth (exceptionClass.getSuperclass (), depth + 1);} @ Transactional is valid only when applied to the public method
Transaction management can occur only if the @ Transactional annotation is applied to the public method.
This is because when using the Spring AOP proxy, before Spring calls TransactionInterceptor to intercept the target method before and after the execution of the target method, the intercept method of DynamicAdvisedInterceptor (the inner class of CglibAopProxy) or the invoke method of JdkDynamicAopProxy will indirectly call the computeTransactionAttribute method of AbstractFallbackTransactionAttributeSource (through this class Spring gets the transaction attribute configuration property information annotated by @ Transactional).
AbstractFallbackTransactionAttributeSource
Protected TransactionAttribute computeTransactionAttribute (Method method, Class targetClass) {/ / Don't allow no-public methods as required. If (allowPublicMethodsOnly () & &! Modifier.isPublic (method.getModifiers () {return null;}
The allowPublicMethodsOnly method is implemented by the subclass AnnotationTransactionAttributeSource, which defaults to true, so when the method annotated by the transaction is not public, the method directly returns null
The property configuration information for @ Transactional is not obtained, resulting in not using TransactionInterceptor to intercept the target method for transaction management.
To avoid the problem of self-calling AOP of Spring, you must call across service
Under the AOP proxy of Spring, only when the target method is called externally (that is, across the service), the target method is managed by the proxy object generated by Spring, which can cause self-calling problems.
If other methods in the same class that do not have @ Transactional annotations call methods with @ Transactional annotations, transactions of methods with @ Transactional annotations are ignored and rollback will not occur.
Example:
-- > @ Servicepublic class OrderService {private void insert () {insertOrder ();} @ Transactional public void insertOrder () {/ / insert log info / / insertOrder / / updateAccount}
Although insertOrder has the @ Transactional annotation, it is called by the internal method insert, the transaction is ignored, and the abnormal transaction will not be rolled back.
The problem of communication of affairs
PROPAGATION_REQUIRES_NEW is only valid across service (also caused by the above self-call)
Class ServiceA {@ Transactional (rollbackFor = Exception.class) public methodA1 () {. / / in this way, transaction comments on methodA2 will not work and new transactions will not be opened, and methodA2 commits or rolls back 1.this.methodA2 () together with data in methodA1; / / in this way, transactions on methodB1 will start 2.ServiceB.methodB1 (). }; @ Transactional (propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public methodA2 () {. };} class ServiceB {@ Transactional (propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public methodB1 () {. };}
The reason is that when a method is called across Service, it passes through the
Org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor.intercept () method
Only through this can the transaction be controlled.
This is the end of the content of "spring annotation configuration method for transaction control and transaction implementation mechanism". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.