1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
   |  
public class BusinessInterceptor implements MethodBeforeAdvice,
                                                    AfterReturningAdvice,
                                                    ThrowsAdvice {
 
    public void before(Method m, Object[] args, Object targetObject)
                throws Throwable {
    	System.out.println("BeforeInterceptor");
        Session session = openSession();
        Transaction t = session.beginTransaction();
        Class[] paramsType = { Session.class };
        Object[] params = { session };
        targetObject.getClass().getMethod("setSession", paramsType)
                    .invoke(targetObject, params);
    }
 
    public void afterThrowing(Method m, Object[] args, Object targetObject,
                              Exception ex) throws Throwable {
    	System.out.println("After");
        closeSession(getSession(targetObject));
        throw new Exception(ex);
    }
 
    private Session getSession(Object targetClass) throws Throwable {
    	System.out.println("getSession");
        return (Session) targetClass.getClass().getMethod("getSession", null)
                                    .invoke(targetClass, null);
    }
 
    private Session openSession() {
    	System.out.println("openSession");
    	return HibernateUtil.getSession();
    }
 
    private void closeSession(Session session) {
    	System.out.println("closeSession");
        if (session != null) {
            session.close();
        }
    }
 
    public void afterReturning(Object returnValue, Method m, Object[] args,
                               Object targetObject) throws Throwable {
    	System.out.println("afterReturing");
        Session session = getSession(targetObject);
        if (session != null) {
            Transaction t = session.getTransaction();
            if (t != null) {
                t.commit();
            }
        }
        closeSession(session);
    } | 
Partager