aop增强注解

增强类

@Aspect
public class LoggerAdvice {
    private static Logger logger=Logger.getLogger(LoggerAdvice.class);
    @Pointcut("execution(* com.kgc..*.*(..))")
    public void pointcut(){}
    //增强前置方法
    @Before("execution(* com.kgc..*.*(..))")
    public void before(JoinPoint js){
        logger.info("调用"+js.getTarget()+"的"+js.getSignature().getName()+"方法。方法入参:"+Arrays.toString(js.getArgs()));
    }
    //增强后置方法
    @AfterReturning(pointcut="execution(* com.kgc..*.*(..))",returning = "result")
    public void afterReturning(JoinPoint js,Object result){
        logger.info("调用"+js.getTarget()+"的"+js.getSignature().getName()+"方法。方法返回值:"+result);
    }
}

二.相同切入点


@Aspect
public class LoggerAdvice {
    private static Logger logger=Logger.getLogger(LoggerAdvice.class);
    @Pointcut("execution(* com.kgc..*.*(..))")
    public void pointcut(){}
    //增强前置方法
    @Before("pointcut()")
    public void before(JoinPoint js){
        logger.info("调用"+js.getTarget()+"的"+js.getSignature().getName()+"方法。方法入参:"+Arrays.toString(js.getArgs()));
    }
    //增强后置方法
    @AfterReturning(pointcut="pointcut()",returning = "result")
    public void afterReturning(JoinPoint js,Object result){
        logger.info("调用"+js.getTarget()+"的"+js.getSignature().getName()+"方法。方法返回值:"+result);
    }
     //afterThrowing增强异常方法
    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint js,RuntimeException e){
        logger.error(js.getSignature().getName()+"方法发生异常,"+e);
    }
    //最终增强方法
    @After("pointcut()")
    public void after(JoinPoint js){
        logger.info(js.getSignature().getName()+"方法结束了,");
    }
    //环绕增强
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint js)throws Throwable{
        logger.info("调用" + js.getTarget() + "的" + js.getSignature().getName() + "方法。方法入参:" + Arrays.toString(js.getArgs()));
        Object result = null;
        try {
            result = js.proceed();
            logger.info("调用" + js.getTarget() + "的" + js.getSignature().getName() + "方法。方法返回值:" + result);

        } catch (Throwable e) {
            logger.error(js.getSignature().getName()+"方法发生异常"+e);
            throw e;
        }finally {
            logger.error(js.getSignature().getName()+"方法执行结束");
        }
        return result;
    }
} 

bean.xml




		//扫描包中注解标注的类
        
        //增强类注解方法所在的包
   	    
        

//测试

@Test
    public void test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
        Printer printer=(Printer)context.getBean("printer");
        String content ="ccdsjkhvdsaivhdsajivhdas";
        printer.print(content);
    }

你可能感兴趣的:(Spring框架)