Spring's things management

Source: Internet
Author: User

I. Definition and characteristics of things

A thing represents a collection of operations. That is, a series of operations for a minimum unit indivisible (atomic), this sequence of operations either all succeed or fail all (consistency), each operation set does not interfere with each other (isolation), the operation of the collection of all operations completed after the data must be stored in a persistent way (persistence).

II. Transaction management of Spring

Spring's transaction management is divided into programmatic things and declarative things.

1, Programming things management

programming Things management based on the underlying API

Programmatic management of things is done based on the three core interfaces of Plateformtransactionmanger, Transactiondefinition, and Transactionstatus.

Example of a thing management code based on the underlying API

1 Public classBankserviceimplImplementsBankservice {2PrivateBankdao Bankdao;3Privatetransactiondefinition txdefinition;4PrivatePlatformtransactionmanager Txmanager;5 ...... 6 Public BooleanTransfer (long fromid, long toid,Doubleamount) { 7 Transactionstatus Txstatus =txmanager.gettransaction (txdefinition);8Booleanresult =false; 9Try {Ten result =Bankdao.transfer (Fromid, toid, amount);11Txmanager.commit (txstatus);12}Catch(Exception e) {result =false;14Txmanager.rollback (txstatus);System.out.println ("Transfer error!");16     }17returnresult;18 }19}

Sample configuration file code based on the underlying API

class class= "Org.springframework.transaction.support.DefaultTransactionDefinition" ><property name= " Propagationbehaviorname "value=" propagation_required "/></bean></property></bean>

Transactiontemplate-based programming for things management

This is the simplified version of the above

 Public classBankserviceimplImplementsBankservice {PrivateBankdao Bankdao;Privatetransactiontemplate transactiontemplate; Public BooleanTransferFinalLong Fromid,FinalLong Toid,Final Doubleamount) {return(Boolean) Transactiontemplate.execute (NewTransactioncallback () { PublicObject Dointransaction (Transactionstatus status) {object result; Try{result=Bankdao.transfer (Fromid, toid, amount); } Catch(Exception e) {status.setrollbackonly (); Result=false; System.out.println ("Transfer error!"); }    returnresult; }});}}

Configuration file Example

<bean id= "Bankservice"class= "Footmark.spring.core.tx.programmatic.template.BankServiceImpl" >< Property Name= "Bankdao" ref= "Bankdao"/><property name= "transactiontemplate" ref= "Transactiontemplate"/> </bean>

The Execute () method of the Transactiontemplate has a parameter of type Transactioncallback, which defines a dointransaction () method, which is usually implemented in the form of an anonymous inner class. The Transactioncallback interface and writes the business logic code in its dointransaction () method. You can use the default transaction commit and rollback rules here, so that you do not need to explicitly invoke any transaction-managed APIs in your business code. The Dointransaction () method has a parameter of type Transactionstatus, and we can call the parameter's Setrollbackonly () method at any point in the method to identify the transaction as rolled back to perform a transaction rollback.

According to the default rule, if an unchecked exception is thrown during the execution of the callback method, or if the Transacationstatus.setrollbackonly () method is explicitly called, the transaction is rolled back, or if the transaction execution completes or throws an exception of type checked, Commits the transaction.

The Transactioncallback interface has a sub-interface transactioncallbackwithoutresult that defines a Dointransactionwithoutresult () method in the interface. The Transactioncallbackwithoutresult interface is primarily used in cases where the return value is not required during a transaction. Of course, for cases where the return value is not required, we can still use the Transactioncallback interface and return any value in the method.

2. Declarative things Management

Spring's declarative transaction management is based on the underlying AOP. The essence is to intercept the method before and after it, and then create or join a transaction before the target method starts, committing or rolling back the transaction according to execution after the target method is executed.

The greatest advantage of declarative transactions is that you do not need to programmatically manage transactions, so that you do not need to mix transaction-managed code in your business logic code, and you can apply transaction rules to business logic by simply making the relevant transaction rule declarations in the configuration file (or through an equivalent label-based approach). Because transaction management is a typical crosscutting logic in itself, it is where AOP comes in. The Spring development team is aware of this and provides simple and powerful support for declarative transactions.

Declarative transaction management was once a highlight of EJB's pride, and now spring has made POJO the same treatment as EJB for transaction management, allowing developers to use a powerful declarative transaction management feature outside of the EJB container, mainly thanks to the Spring-dependent injection container and SPR ing AOP support. The Dependency injection container provides the infrastructure for declarative transaction management, which makes the Bean manageable for the spring framework, while Spring AOP is the direct implementation of declarative transaction management, as shown in Listing 8.

In general, I strongly recommend the use of declarative transactions in development, not only because of its simplicity, but mainly because it makes the pure business code is not contaminated, greatly facilitates the later code maintenance.

The only disadvantage of declarative transactions, compared to programmatic transactions, is that the finer granularity of the latter only works at the method level and cannot be scoped to the code block as a programmatic transaction. But even with this requirement, there are many workarounds, such as the ability to separate code blocks that require transaction management into methods, and so on.

Here's a look at the declarative transaction management capabilities that Spring provides for us.

Based on Transactioninter ... Declarative transaction Management for

Spring provides the Transactioninterceptor class to implement declarative transaction management functionality.

<beans...>......<bean id= "Transactioninterceptor"class= "Org.springframework.transaction.interceptor.TransactionInterceptor" ><property name= "TransactionManager" ref= "TransactionManager"/><property name= "transactionattributes" ><props><prop key= "Transfer" >propagation_required</prop></props></property></bean><bean id= "BankServiceTarget "class= "Footmark.spring.core.tx.declare.origin.BankServiceImpl" ><property name= "Bankdao" ref= "Bankdao"/></ Bean><bean id= "Bankservice"class= "Org.springframework.aop.framework.ProxyFactoryBean" ><property name= "target" ref= "Bankservicetarget"/> <property name= "Interceptornames" ><list><idref bean= "Transactioninterceptor"/></list> </property></bean>......</beans>
Based on Transactionproxy ... Declarative transaction Management for
<beans......> ... <bean id= "Bankservicetarget"class= "Footmark.spring.core.tx.declare.classic.BankServiceImpl" >< Property Name= "Bankdao" ref= "Bankdao"/></bean><bean id= "Bankservice"class= " Org.springframework.transaction.interceptor.TransactionProxyFactoryBean "><property name=" target "ref=" Bankservicetarget "/><property name=" TransactionManager "ref=" TransactionManager "/><property name=" Transactionattributes "><props><prop key=" Transfer ">propagation_required</prop></props ></property></bean> ... </beans>
Declarative transaction management based on the <tx> namespace

The first two declarative transaction configuration methods provide the cornerstone of Spring declarative transaction management. Based on this, Spring 2.x introduces the <tx> namespace, combined with the use of <aop> namespaces, to give developers a new experience of configuring declarative transactions, which makes configuration simpler and more flexible. Also, declarative transactions become more powerful, thanks to the pointcut expression support of the <aop> namespace.

<beans......>......<bean id= "Bankservice" class= " Footmark.spring.core.tx.declare.namespace.BankServiceImpl "><property name=" Bankdao "ref=" Bankdao "/>< /bean><tx:advice id= "Bankadvice" transaction-manager= "TransactionManager" ><TX:ATTRIBUTES><TX: Method Name= "Transfer" propagation= "REQUIRED"/></tx:attributes></tx:advice> <aop:config>< Aop:pointcut id= "bankpointcut" expression= "Execution (* *.transfer (..))" /><aop:advisor advice-ref= "Bankadvice" pointcut-ref= "Bankpointcut"/></aop:config>......</beans >

If the default transaction properties meet the requirements, the code is simplified to

<beans......> ... <bean id= "Bankservice"class= "Footmark.spring.core.tx.declare.namespace.BankServiceImpl" >< Property Name= "Bankdao" ref= "Bankdao"/></bean><tx:advice id= "Bankadvice" transaction-manager= " TransactionManager "><aop:config><aop:pointcut id=" bankpointcut "expression=" Execution (**.transfer (..)) " /><aop:advisor advice-ref= "Bankadvice" pointcut-ref= "bankpointcut"/></aop:config>... </beans>

Because tangent expressions are used, we do not need to create a proxy object for each business class. Also, if the name of the configured transaction manager Bean is "TransactionManager", then we can omit the Transaction-manager property of <tx:advice> because the default value for this property is " TransactionManager ".

Declarative transaction management based on @Transactional

In addition to the namespace-based transaction configuration, Spring 2.x introduces a Annotation-based approach, mainly involving @transactional annotations. @Transactional can be used on interfaces, interface methods, classes, and class methods. When used on a class, all public methods of the class will have transactional properties of that type, and at the method level we can also use the callout to override the class-level definition.

@Transactional (propagation = propagation.required)publicbooleandouble  Amount) {return  bankdao.transfer (fromid, toid, amount);}

Spring uses beanpostprocessor to handle annotations in the bean, so we need to make the following declaration in the configuration file to activate the post-processing bean

Enable processing beans

<tx:annotation-driven transaction-manager= "TransactionManager"/>

Similar to the previous, the default value of the Transaction-manager property is TransactionManager, which can be omitted if the name of the transaction manager Bean is the value.

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

The <tx> namespace and @Transactional-based transaction declaration approach have advantages and disadvantages. The advantage of the <tx>-based approach is that it combines with the pointcut expression and is powerful. With pointcut expressions, a configuration can match multiple methods, and @Transactional-based approach must be annotated with @Transactional on every method or class that needs to use the transaction, although the rules for most transactions may be consistent, but Transactional, it is also not reusable and must be specified individually. On the other hand, the use of @Transactional-based approach is simple and straightforward, with no learning costs. Developers can choose one or both of these options as needed, or even mix them as needed.

If you are not maintaining the legacy code, it is not recommended to use Transactioninterceptor-based and Transactionproxyfactorybean-based declarative transaction management, but learning these two approaches is very beneficial to understanding the underlying implementation.

    • Programmatic transaction management based on Transactiondefinition, Platformtransactionmanager, and Transactionstatus is the most primitive way Spring provides, and we don't usually write that But understanding this approach has a great effect on understanding the nature of Spring's transaction management.
    • Transactiontemplate-based, programmatic transaction management is the encapsulation of the previous approach, making coding simpler and clearer.
    • Transactioninterceptor-based declarative transactions are the basis of spring declarative transactions and are not generally recommended, but as before, understanding this approach has a significant effect on understanding Spring declarative transactions.
    • Transactionproxyfactorybean-based declarative transactions are an improved version of the Chinese-style, simplified configuration file writing, which is a declarative transaction management approach recommended by spring in the early days, but is not recommended in Spring 2.0.
    • Declarative transaction management based on <tx> and <aop> namespaces is the current recommended approach, with the greatest feature of combining Spring AOP with the strong support of pointcut expressions to make management transactions more flexible.
    • The @Transactional-based approach simplifies declarative transaction management to the extreme. Developers simply add a line to the configuration file to enable the configuration of the related post-processing Bean, and then use the @Transactional to specify transaction rules on methods or classes that need to implement transaction management to achieve transaction management, and do not have the same functionality in other ways.

  

Spring's things management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.