Declarative transactions using Tiger annotations
Hello All!
:idea:
I just want to share the code, that allow using JDK 5 annotations for declarative transactions.
Transacted.java:
Code:
package spring.transaction;
import java.lang.annotation.*;
import org.springframework.transaction.TransactionDefinition;
/**
* @author Sergey Astakhov
* @see spring.transaction.JDK5TransactionAttributeSource
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Transacted
{
int propagation() default TransactionDefinition.PROPAGATION_REQUIRED;
int isolation() default TransactionDefinition.ISOLATION_DEFAULT;
boolean readOnly() default false;
}
JDK5TransactionAttributeSource.java
Code:
package spring.transaction;
import java.lang.reflect.Method;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
/**
* @author Sergey Astakhov
*/
public class JDK5TransactionAttributeSource implements TransactionAttributeSource
{
public TransactionAttribute getTransactionAttribute(Method method, Class targetClass)
{
Transacted desc = method.getAnnotation(Transacted.class);
if( desc==null )
{
if( targetClass==null ) targetClass = method.getDeclaringClass();
desc = (Transacted) targetClass.getAnnotation(Transacted.class);
if( desc==null ) return null;
}
DefaultTransactionAttribute attr = new DefaultTransactionAttribute();
attr.setPropagationBehavior( desc.propagation() );
attr.setIsolationLevel( desc.isolation() );
attr.setReadOnly( desc.readOnly() );
return attr;
}
}
declarativeTransactions.xml
Code:
<?xml version="1.0" encoding="Windows-1251"?>
<!DOCTYPE beans
PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="autoproxy"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<bean id="transactionAttributeSource"
class="spring.transaction.JDK5TransactionAttributeSource"
/>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="transactionAttributeSource"><ref bean="transactionAttributeSource"/></property>
</bean>
<bean id="transactionAdvisor"
class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<constructor-arg><ref bean="transactionInterceptor"/></constructor-arg>
</bean>
</beans>
Usage:
Code:
@Transacted
public class ServiceImpl implements Service
{
@Transacted( readOnly=true )
public Set<EntityInfo> getEntityList()
{
...
}
public void deleteEntity(EntityInfo info)
{
...
}
}
We are using this code in our project - works very nice.
:D