ServiceProxy.javajava
package proxy; import exception.BusinessException; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.Random; @Component @Aspect public class ServiceProxy { private final static Logger LOGGER = Logger.getLogger(ServiceProxy.class); @Around("execution(* service..*.*(..))") public Object around(ProceedingJoinPoint point) throws Throwable { Object[] args = point.getArgs(); // 參數 LOGGER.info("request begin args[" + Arrays.toString(args) + "]."); Object returnValue = null; try { returnValue = point.proceed(args); } catch (BusinessException e) { LOGGER.info("catch business exception."); returnValue = "business exception"; } catch (Exception e) { LOGGER.info("catch runtime exception."); returnValue = "runtime exception"; } return returnValue; } @Before("execution(* service..*.*(..))") public void before(JoinPoint point) throws Throwable { int randomNumber = new Random().nextInt(50); if (randomNumber % 2 == 0) { throw new BusinessException("no power."); } LOGGER.info("congratulation!"); } @AfterReturning(pointcut = "execution(* service..*.*(..))", returning="returnValue") public void afterReturning(JoinPoint point, Object returnValue) throws Throwable { LOGGER.info("return value[" + returnValue + "]."); } @After("execution(* service..*.*(..))") public void after(JoinPoint point) throws Throwable { LOGGER.info("Bey bey!"); } }
Spring配置spring
<context:component-scan base-package="proxy"></context:component-scan> <aop:aspectj-autoproxy proxy-target-class="true" />