Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize transaction nesting in spring

Shulou Source: shulou.com Published: 2022-06-02 10:32:10 09月20日 Update

This article is to share with you about how to achieve transaction nesting processing in spring, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

The principle of spring transaction is dynamic proxy. When the transaction is nested, only the first method executed has the transaction, and the second nested method will be executed as an ordinary method, so we need to get the current proxy class again and generate the transaction again by the proxy. The specific processing methods are as follows: 1. Write a utility class to get the current service.

@ Componentpublic class SpringUtil implements ApplicationContextAware {private static ApplicationContext applicationContext; @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {if (SpringUtil.applicationContext = = null) {SpringUtil.applicationContext = applicationContext;} System.out.println ("= ApplicationContext configuration is successful. In a normal class, you can get the applicationContext object by calling SpringUtils.getAppContext (), applicationContext=" + SpringUtil.applicationContext+ "="). System.out.println ("-");} / / get applicationContext public static ApplicationContext getApplicationContext () {return applicationContext;} / / get Bean through name. Public static Object getBean (String name) {return getApplicationContext (). GetBean (name);} / / get Bean through class. Public static T getBean (Class clazz) {return getApplicationContext () .getBean (clazz);} / / return the specified Bean public static T getBean (String name,Class clazz) {return getApplicationContext () .getBean (name, clazz) through name and Clazz;}}

2. Get the current proxy class, convert it to the current service, and then call the nested method.

((EntityService) AopContext.currentProxy ()) .updateById (entity)

If your code reports an error after this, please add this comment to the class

@ EnableAspectJAutoProxy (proxyTargetClass = true, exposeProxy = true)

The above is how to achieve transaction nesting processing in spring. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Transactions methods agents processing ordinary code more knowledge articles practical successful dynamic principles only can pass objects that is work meetings tools articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Information vpn Huawei Microsoft