Java tutorial
/* * Copyright (C) 2009, 2010 M. Lechouga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mb.bo; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.mb.exception.OrmException; import org.mb.session.SessionFactory; import java.util.logging.Logger; /** * Spring interceptor that intercepts all service method calls, making service * methods transactional. * <p> * It simply executes SessionFactory.getCurrentSession().beginTransaction() * before each call, and after it, invokes * SessionFactory.getCurrentSession().commit()/.rollback() depending if an * exception is catched. * <p> * Here a configuration example: * * <pre> * <bean id="txInterceptor" class="org.sorm.tx.TxInterceptor" /> * <bean id="abstractService" abstract="true"> * <property name="interceptorNames"> * <list><value>txInterceptor</value></list> * </property> * </bean> * <bean id="exampleService" class="org.springframework.aop.framework.ProxyFactoryBean" * parent="abstractService"> * <property name="proxyInterfaces" value="org.sorm.example.bo.ExampleService" /> * <property name="target"> * <bean class="org.sorm.example.bo.ExampleServiceImpl"> * <property name="personDao" ref="personDao" /> * <property name="cityDao" ref="cityDao" /> * </bean> * </property> * </bean> *</pre> * <p> * For a less verbose Spring configuration, see * {@link org.sorm.spring.tx.SpringTxServiceFactory}. * * @see org.sorm.spring.tx.SpringTxServiceFactory * @see SessionFactory * @author mhoms */ public class SpringTxInterceptor implements MethodInterceptor { private final static Logger LOG = Logger.getLogger(SpringTxInterceptor.class.getName()); /** * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) */ public Object invoke(final MethodInvocation invocation) throws Throwable { final Method method = invocation.getMethod(); SessionFactory.getSession().open(); try { LOG.finer("invoking service method: " + method.toString()); final Object result = method.invoke(invocation.getThis(), invocation.getArguments()); SessionFactory.getSession().commit(); return result; } catch (final Exception e) { SessionFactory.getSession().rollback(); throw new OrmException("error during execution of service method: " + invocation.toString(), e); } } }