Skip to Main Content
Spring: A Developer's Notebook
book

Spring: A Developer's Notebook

by Bruce Tate, Justin Gehtland
April 2005
Intermediate to advanced content levelIntermediate to advanced
216 pages
4h 44m
English
O'Reilly Media, Inc.
Content preview from Spring: A Developer's Notebook

Building a Test-Friendly Interceptor

In this example, you'll learn how to build interceptors that do nothing but improve your ability to test code. Usually, a transaction interceptor does three things:

  1. Begins a transaction when a method starts.

  2. Rolls back a transaction when an exception is thrown.

  3. Commits the transaction when a method completes.

Of course, that's what you usually want to happen. Test cases are different animals, though. They're responsible for putting conditions back to the state where they were before a test case was fired, and they need to execute quickly.

For a test case, often it makes sense to replace the third step. You may instead want the transaction to roll back after the method completes. That way, you remove one of the most expensive database steps (the commit), and you also restore the database state to what it was before you executed the transaction.

How do I do that?

In Spring, it's easy to build this type of behavior into an interceptor, because you can build a custom interceptor. Example 7-29 shows the code for a transaction interceptor that rolls back.

Example 7-29. TestTxInterceptor.java

public class TestTxInterceptor implements MethodInterceptor { private PlatformTransactionManager platformTransactionManager; public PlatformTransactionManager getPlatformTransactionManager( ) { return platformTransactionManager; } public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) { this.platformTransactionManager = platformTransactionManager; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaBeans Unleashed

JavaBeans Unleashed

Dr. Donald Doherty, Rick Leinecker
Beginning Spring

Beginning Spring

Mert Caliskan, Kenan Sevindik, Rod Johnson, Jürgen Höller
Hibernate Search in Action

Hibernate Search in Action

Emmanuel Bernard, John Griffin

Publisher Resources

ISBN: 0596009100Supplemental ContentErrata Page