public class TxProgrammaticSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:tx-programmatic-app-context.xml");
ctx.refresh();
ContactService contactService = ctx.getBean("contactService",
ContactService.class);
System.out.println("Contact count: " + contactService.countAll());
}
}
We will leave it to you to run the program and observe the result. Try to tweak the transaction
attributes and see what happens in the transaction processing of the countAll() method.
Considerations on Transaction Management
So, having discussed the various ways for implementing transaction management, which one should
you use? The declarative approach is recommended in all cases, and you should avoid implementing
transaction management within your code as far as possible. Most of the time when you find it necessary
to code transaction control logic in the application, it is because of bad design, and in this case, you
should consider refactoring your logic into manageable pieces and have the transaction requirements
defined on those pieces declaratively.
For the declarative approach, using XML and using annotations both have their own pros and cons.
Some developers prefer not to declare transaction requirements in code, while others prefer using
annotations for easy maintenance, because you can see all the transaction requirement declaration
within the code. Again, let the application requirements drive your decision, and once your team or
company has standardized on the approach, stay consistent with the configuration style.
Global Transactions with Spring
Many enterprise Java applications will need to access multiple backend resources. For example, a piece
of customer information received from an external business partner will need to update the databases
for multiple systems (CRM, ERP, and so on). Some will even need to produce a message and send it to an
MQ server via JMS for all other applications within the company that are interested in customer
information. Transactions that span multiple backend resources are referred to as global (or distributed)
transactions.
A main characteristic of a global transaction is the guarantee of atomicity, which means that
involved resources are all updated or none is updated. This includes complex coordination and
synchronization logic that should be handled by the transaction manager. In the Java world, JTA is the
de facto standard for implementing global transactions.
Spring supports JTA transactions equally well as local transactions and hides that logic from the
business code. In this section, we will demonstrate how to implement global transactions by using JTA
with Spring.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home