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

How to implement declarative transaction and programmatic transaction in Spring

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article shows you how to implement declarative transactions and programmatic transactions in Spring. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Declarative and programmatic transactions

Declarative transactions are implemented based on agents. The smallest force is at the method level. Programmatic transactions are based on transaction templates and are highly aggressive and are not recommended.

Programmatic transaction management programmatic transaction management based on underlying API

According to the three core interfaces of PlatformTransactionManager, TransactionDefinition and TransactionStatus, we can manage transactions programmatically. The sample code is shown in listing 4:

Public class BankServiceImpl implements BankService {private BankDao bankDao;// transaction definition private TransactionDefinition txDefinition;// transaction Manager private PlatformTransactionManager txManager;.public boolean transfer (Long fromId, Long toId, double amount) {/ / transaction status TransactionStatus txStatus = txManager.getTransaction (txDefinition); boolean result = false;try {result = bankDao.transfer (fromId, toId, amount); txManager.commit (txStatus);} catch (Exception e) {result = false;txManager.rollback (txStatus); System.out.println ("Transfer Error!") } return result;}}

Listing 5. Sample configuration file of transaction management based on underlying API

Programmatic transaction Management public class BankServiceImpl implements BankService {private BankDao bankDao;private TransactionTemplate transactionTemplate;.public boolean transfer (final Long fromId, final Long toId, final double amount) {return (Boolean) transactionTemplate.execute (new TransactionCallback () {public Object doInTransaction (TransactionStatus status) {Object result) based on TransactionTemplate Try {result = bankDao.transfer (fromId, toId, amount);} catch (Exception e) {status.setRollbackOnly (); result = false System.out.println ("Transfer Error!");} return result;}})

The corresponding XML configuration is as follows:

Listing 7. Sample configuration file for transaction management based on TransactionTemplate

Declarative transaction management based on TransactionInter... Declarative transaction management based on

Listing 8. Sample configuration file for transaction management based on TransactionInterceptor. PROPAGATION_REQUIRED.

Based on TransactionProxy... Declarative transaction management based on

Listing 9. Sample configuration file for transaction management based on TransactionProxyFactoryBean. PROPAGATION_REQUIRED.

Declarative transaction management based on namespace

Listing 10. Based on the transaction management sample configuration file. Tx:attributes

Aop:config. If the default transaction attributes meet the requirements, the code is simplified as shown in listing 11:

Listing 11. A simplified sample configuration file for transaction management based on. Aop:config. Because of the use of pointcut expressions, we do not need to create a proxy object for each business class. In addition, if the name of the configured transaction manager Bean is "transactionManager", we can omit the transaction-manager property of tx:advice because the default value of this attribute is "transactionManager".

Declarative transaction Management based on @ Transactional

In addition to the namespace-based transaction configuration, Spring 2.x also introduces an Annotation-based approach, which mainly involves @ Transactional annotations. @ Transactional can act on interfaces, interface methods, classes, and class methods. When acting on a class, all public methods of that class will have transactional properties of that type, and we can also use this annotation at the method level to override the class-level definition. As shown in listing 12:

Listing 12. The @ Transactional-based sample transaction management configuration file @ Transactional (propagation = Propagation.REQUIRED) public boolean transfer (Long fromId, Long toId, double amount) {return bankDao.transfer (fromId, toId, amount);} Spring uses BeanPostProcessor to process annotations in Bean, so we need to make the following declaration in the configuration file to activate the post-processing Bean, as shown in listing 13:

Listing 13. The configuration for enabling post-processing Bean is similar to the previous one, and the default value for the transaction-manager attribute is transactionManager, which can be omitted if the name of the transaction manager Bean is that value.

Although the @ Transactional annotation can be applied to interfaces, interface methods, classes, and class methods, the Spring team recommends that it not be used on interfaces or interface methods, because it only takes effect when using interface-based proxies. In addition, the @ Transactional annotation should only be applied to public methods, which is determined by the nature of Spring AOP. If you use the @ Transactional annotation on protected, private, or default visibility methods, this will be ignored and no exception will be thrown.

Namespace-based and @ Transactional-based transaction declaration methods have their own advantages and disadvantages. Based on the method, its advantage is that it is powerful in combination with pointcut expressions. With pointcut expressions, a configuration can match multiple methods, and the @ Transactional-based approach must be marked with @ Transactional on each method or class that needs to use a transaction. Although the rules for most transactions may be consistent, for @ Transactional, they cannot be reused and must be specified one by one. On the other hand, the @ Transactional-based approach is very straightforward to use and has no learning cost. Developers can use either of them as needed, or even mix the two as needed.

If you are not maintaining legacy code, it is no longer recommended to use TransactionInterceptor-based and TransactionProxyFactoryBean-based declarative transaction management, but learning these two approaches is very useful for understanding the underlying implementation.

Although the above lists a total of four declarative transaction management methods, but this division is only for ease of understanding, in fact, the implementation of the background is the same, but the way users use it is different.

Summary

Programmatic transaction management based on TransactionDefinition, PlatformTransactionManager, and TransactionStatus is the most primitive way that Spring provides, which we don't usually write about, but understanding this approach is very useful in understanding the nature of Spring transaction management.

Programmatic transaction management based on TransactionTemplate is an encapsulation of the previous way, which makes the coding simpler and clearer.

TransactionInterceptor-based declarative transactions are the basis of Spring declarative transactions, and this approach is generally not recommended, but as before, understanding this approach is very useful in understanding Spring declarative transactions.

TransactionProxyFactoryBean-based declarative transaction is an improved version of the above-mentioned approach, simplified configuration file writing, which is an early recommendation of Spring declarative transaction management, but is no longer recommended in Spring 2.0.

Declarative transaction management based on and namespace is currently recommended, and its biggest feature is that it is closely integrated with Spring AOP, which can make full use of the strong support of pointcut expressions and make transaction management more flexible.

The @ Transactional-based approach simplifies declarative transaction management to the extreme. Developers only need to add a line to the configuration file to enable the relevant post-processing Bean configuration, and then use @ Transactional to specify transaction rules on the methods or classes that need to implement transaction management, and the functionality does not have to be inferior in other ways.

The above is how to implement declarative and programmatic transactions in Spring. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are 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

Internet Technology

Wechat

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

12
Report