Sometimes it is necessary to use portions of Spring without having access to the applicationContext.xml setup. In this case, I wanted to use AOP to wrap my DAO methods in transaction code; the DAO is in a jar built independently from the webapps. So, I did the following.

DeploymentDAO is an interface; DeploymentDAOIbatis is an implementation of it.


ProxyFactory pf = new ProxyFactory();
pf.addInterface(DeploymentDAO.class);
pf.setTarget(new DeploymentDAOIbatis(ds));
Properties p = new Properties();
p.setProperty("save*", "ISOLATION_REPEATABLE_READ");
p.setProperty("remove*", "ISOLATION_REPEATABLE_READ");
p.setProperty("*", "PROPAGATION_REQUIRED,readOnly");
TransactionInterceptor ti = new TransactionInterceptor();
ti.setTransactionAttributes(p);
ti.setTransactionManager(new DataSourceTransactionManager(ds));
pf.addAdvisor(new TransactionAttributeSourceAdvisor(ti));
return (DeploymentDAO) pf.getProxy();

The equivalent applicationContext.xml code would be, approximately:


<bean id="deploymentDAO"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
        <ref bean="transactionManager"/>
    </property>
    <property name="target">
        <ref bean="blah.dao.DeploymentDAOIbatis"/>
    </property>
    <property name="transactionAttributes">
        <props>
            <prop key="save*">ISOLATION_REPEATABLE_READ</prop>
            <prop key="remove*">ISOLATION_REPEATABLE_READ</prop>
            <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
        </props>
    </property>
</bean>

UPDATE:

Here is better code.


Properties p = new Properties();
p.setProperty("obtain*", "PROPAGATION_REQUIRED, ISOLATION_SERIALIZABLE");
p.setProperty("create*", "PROPAGATION_REQUIRED, ISOLATION_REPEATABLE_READ");
p.setProperty("update*", "PROPAGATION_REQUIRED, ISOLATION_REPEATABLE_READ");
p.setProperty("remove*", "PROPAGATION_REQUIRED, ISOLATION_REPEATABLE_READ");
p.setProperty("*", "PROPAGATION_REQUIRED,readOnly");
TransactionProxyFactoryBean tpfb = new TransactionProxyFactoryBean();
tpfb.setTransactionManager(new DataSourceTransactionManager(ds));
tpfb.setTransactionAttributes(p);
tpfb.setTarget(new DeploymentDaoIbatis(ds));
tpfb.afterPropertiesSet();
return (DeploymentDao) tpfb.getObject();


Related Leave a Comment