Learn about the basic framework of Spring transaction management (see below). On this basis, spring also mentions declarative transaction management and programmatic transaction management. Here's a look at how spring is implemented.
Spring declarative Transactions vs. EJB transaction Management
Spring's declarative management, similar to EJB's CMT, is different. The differences between them are:
1) The CMT for EJBS is used in conjunction with JTA, while the spring framework's declarative transaction management can work in any environment. You can use both global transaction management, such as JTA, and local transaction management such as JDBCJPA, Hibernate, JDO, and so on.
2) You can use spring's declarative transaction management in any class. But EJB is not, it can only be used in a particular class.
3) Spring provides some of the different rollback principles in EJB (there are rollback principles, but some in spring are different from EJBS). These rollback principles are available in both programmatic transaction management and declarative transaction management.
4) The spring framework allows you to customize some of the transactional behavior using the AOP approach. In EJB, it is not possible.
5) The Spring framework does not support remote invocation of the transaction propagation mechanism context. EJB is required if the application needs to support the transaction propagation mechanism at remote invocation.
Spring Declarative Transaction Management
Spring declarative transaction management is implemented (viewed) using the AOP principle. Before looking at the source of spring AOP, it is known that spring AOP is done by creating proxies (CGI proxies or JDK proxies (viewing)), invoking an AOP interceptor chain, and then invoking real processing to return the results.
Next look at how Spring declarative transaction management is implemented:
According to, you can guess: when the caller executes a method call, the spring container creates an AOP proxy for it, gets its interceptor based on the proxy, invokes the Interceptor chain processing, then makes the method call, the last interceptor chain does the post processing, and returns the result.
Transaction management is the emergence of a advistor, Advistor, is the holder of advice, through which can find advice, that is enough to find interceptor, So it's easy to understand that spring is putting transaction processing as an interceptor in front of other interceptors.
The above is based on the invocation flowchart guessing, and then look at how it is handled in spring:
Transactionattributesourceadvistor is the advistor in the schematic diagram above, but also the Advistor SPRINGAOP to use. In his interior, there is indeed an interceptor transactioninterceptor. Next look at this interceptor (see the main section only):
Public classTransactioninterceptorextendsTransactionaspectsupportImplementsMethodinterceptor, Serializable { PublicObject Invoke (FinalMethodinvocation invocation)throwsThrowable {//Work out the target class:may is <code>null</code>. //The Transactionattributesource should be passed the target class//as well as the method, which may is from an interface.Class<?> Targetclass = (Invocation.getthis ()! =NULL? Aoputils.gettargetclass (Invocation.getthis ()):NULL); //If The transaction attribute is null, the method is non-transactional. FinalTransactionAttribute txattr =Gettransactionattributesource (). Gettransactionattribute (Invocation.getmethod (), targetclass);//fetch to Platformtransactionmanager transaction management Object FinalPlatformtransactionmanager TM =Determinetransactionmanager (txattr); FinalString joinpointidentification =methodidentification (Invocation.getmethod (), targetclass); if(Txattr = =NULL|| ! (tminstanceofCallbackpreferringplatformtransactionmanager)) { //Standard transaction demarcation with Gettransaction and Commit/rollback calls.Transactioninfo Txinfo=Createtransactionifnecessary (tm, Txattr, joinpointidentification); Object RetVal=NULL; Try { //This is a around Advice:invoke the next interceptor in the chain. //This would normally result in a target object being invoked.//Call the Interceptor chain for other interceptors (AOP recommendations) to process, and finally call the target methodRetVal=invocation.proceed (); } Catch(Throwable ex) {//Target Invocation Exception//throw exceptions when necessarycompletetransactionafterthrowing (Txinfo, ex); Throwex; } finally{cleanuptransactioninfo (txinfo); }//Transaction Commitcommittransactionafterreturning (Txinfo); returnRetVal; } Else {//treatment for Websphereuowtransactionmanager. //It ' s a callbackpreferringplatformtransactionmanager:pass a transactioncallback in. Try{Object result=((Callbackpreferringplatformtransactionmanager) TM). Execute (txattr,NewTransactioncallback<object>() { PublicObject dointransaction (transactionstatus status) {Transactioninfo txinfo=Preparetransactioninfo (tm, Txattr, joinpointidentification, status); Try { returninvocation.proceed (); } Catch(Throwable ex) {if(Txattr.rollbackon (ex)) {//a runtimeexception:will leads to a rollback. if(exinstanceofruntimeexception) { Throw(RuntimeException) ex; } Else { Throw NewThrowableholderexception (ex); } } Else { //a normal return value:will leads to A commit. return NewThrowableholder (ex); } } finally{cleanuptransactioninfo (txinfo); } } }); //Check result:it might indicate a throwable to rethrow. if(ResultinstanceofThrowableholder) { Throw((throwableholder) result). Getthrowable (); } Else { returnresult; } } Catch(Throwableholderexception ex) {ThrowEx.getcause (); } } }}
View Code
Obviously, the code here validates my guess on the spring transaction model diagram above. This is thanks to the previous understanding of AOP (view, view). In addition, if there is no previous source of learning, and directly see this part, it is difficult to understand.
From this part of the source code, we see the spring default to help us handle the exception. So when we write code, we can not do exception handling.
Two ways to configure declarative transactional processing
Because the underlying declarative transaction processing is implemented using AOP. So there are two ways to configure declarative transactions in your project: using XML or using @transactional
Configure using XML:
Annotation Mode configuration:
Add the annotations to the code:
For an understanding of attributes such as Readonly,proagation, the previous blog (view) has been studied.
Spring-Programmed Transaction management
As the name implies, we write our own code about transaction processing when we are dealing with business logic.
Spring is still using the template method pattern when it comes to spring programmatic transactions, and spring is a time-proven model.
The previous article also said Spring recommends using Transactiontemplate to complete the processing of programmatic transactions. See how the Template method is written:
Public<T> T Execute (transactioncallback<t> action)throwsTransactionException {if( This. TransactionManagerinstanceofCallbackpreferringplatformtransactionmanager) { return((Callbackpreferringplatformtransactionmanager) This. TransactionManager). Execute ( This, action); } Else{transactionstatus Status= This. Transactionmanager.gettransaction ( This); T result; Try{result=action.dointransaction (status); } Catch(RuntimeException ex) {//Transactional code threw application exception-rollbackrollbackonexception (status, ex); Throwex; } Catch(Error err) {//Transactional code threw error-rollbackrollbackonexception (status, Err); Throwerr; } Catch(Exception ex) {//transactional code threw unexpected exception-rollbackrollbackonexception (status, ex); Throw NewUndeclaredthrowableexception (ex, "Transactioncallback threw undeclared checked exception"); } This. Transactionmanager.commit (status); returnresult; } }
View Code
A template method with a callback function is used to deal with (do not understand can refer to template method mode). Let's write the business logic code for the actual transaction in the callback function. This template does two things for us: 1) transaction management, 2) exception handling.
When we use this, we just need to:
Using a programmatic transaction, you can also use the Platformtransactionmanager implementation class directly to do this:
For example
This is not explained in detail, and this is closely related to the knowledge in the previous section. Because it is difficult to write, it is not recommended.
How to choose?
If your project is small, only a small number of update operations, you can use programmatic transactions, that is, using Transactiontemplate. In addition to this, it is recommended to use declarative transactional processing, which is convenient and requires only a centralized processing of business logic.
Of course, to use a good declarative transaction processing, the previous blog content can be very important yo.