Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Annotation configuration transaction Control in Spring Framework

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you the "Spring framework annotation configuration transaction control example analysis", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "Spring framework annotation configuration transaction control example analysis" this article.

Annotation-based transaction control

Configuring transaction control based on annotations is simpler than XML configuration, but it still requires XML to provide dependencies and cannot completely get rid of XML. The preparatory work is more or less the same as the XML configuration. It is recommended that you learn the XML configuration transaction control before you learn the annotation-based configuration.

All the XML configurations for this test are given here, and the details are described in turn.

1. Configure transaction manager 2. Use @ Transactional annotations in the business tier

You just need to add @ Transactional to the business layer implementation class.

The properties of this annotation have the same meaning as those in xml. This annotation can appear on interfaces, classes, and methods.

Appears on the interface, indicating that all implementation classes of the interface have transaction support.

Appears on the class, indicating that all methods in the class have transaction support

Appears on the method, indicating that the method has transaction support.

Priority of the above three locations: method > class > interface

Package com.gql.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.gql.dao.UserDao;import com.gql.entity.User;/** * class description: * Business layer implementation class * @ guoqianliang1998. * / @ Transactionalpublic class UserServiceImp implements UserService {private UserDao userDao; public void setUserDao (UserDao userDao) {this.userDao = userDao;} @ Override public void save (User user) {userDao.save (user); int I = 1and0 } @ Override public void update (int id, User user) {userDao.update (id, user);} @ Override public void delete (int id) {userDao.delete (id);} @ Override public User getUser (int id) {User user = userDao.getUser (id) Return user;} @ Override public List getUserList (int [] ids) {List userList = userDao.getUserList (ids); return userList;} @ Override public List getUserList () {List list = userDao.getUserList (); return list;}} 3. Enable spring support for annotated transactions 4. Annotation scanner Spring annotation transaction implementation mechanism 1. The implementation mechanism of transaction

AOP dynamic agent 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.

two。 Notes on 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.

TransactionDefinition.PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.

TransactionDefinition.PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.

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.

Transaction propagation problem PROPAGATION_REQUIRES_NEW is only valid across service (also caused by self-invocation above)

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, which is the only way to control the transaction.

These are all the contents of the article "sample Analysis of Annotation configuration transaction Control in the Spring Framework". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report