Mittwoch, 3. Dezember 2008

Annotation-driven transactions

Instead of programmatically implementing code or configuring Spring applicaton context xml files to manage transactions, it can simply be done by using Spring's transaction annotations. There's really not much to it. All you need to do is add the following to your Spring context:

<tx:annotation-driven />

Additionally ensure that the tx namespace is defined as per the xsi:schemaLocation

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.1.xsd"
default-lazy-init="true" />


And now to the fun part! Add annotations to your code. I prefer to apply annotations to interfaces. That way all implementations of the interface are transactional.



...and Bob's your uncle!

1 Kommentar:

Karsten Gresch hat gesagt…

Hi,

the Spring team recommends *not* using @Transactional in interfaces but only in concrete classes.

Reason is that you are bound to interface-based proxies. As annotations are not inherited you wouldn't be able to use cglib proxies or weaving-based aspects. Check the reference, http://tr.im/2f12 and rock on, star :-)

Regards from Berlin,

Karsten

Follower