【框架学习】AOP切面详解

spring、springMVC、SpringBoot这一系列对AOP都有很好的支持(其实都是Spring管理的)



一。概念

(1)面向切面编程,实际上就是给某个方法(或者某些),做一个代理,,很抽象?代理模式详解
代理可以抽象出来,为类似方法进行代理,,从而降低代码量,(相同的功能,如关闭流什么的,只写一次,不仅方便维护,大大减少了工作量

(2)切点,
指的是,对那个方法进行代理,或者某些方法。
切点方法需要 @Pointcut

 @Pointcut("execution(public * xatu.zsl.contoller.*.*(..))")
    public void poincut(){}

(3)通知
即对 被代理方法,加上的操作。

  • 前置通知 @Before(“poincut()”)
  • 后置通知 @After(“poincut()”)
  • 返回时通知 @AfterReturning(pointcut = “poincut()”,returning = “object”) returning指定返回对象。
  • 抛出异常时通知 @AfterThrowing(“poincut()”)
  • 环绕通知 @Around(“poincut()”)



二。使用

前置通知 @Before(“poincut()”)

    @Before("poincut()")
    public void before(JoinPoint joinPoint){
       logger.info("before");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取URL
        logger.info("url={}",request.getRequestURL());
        //请求方法
        logger.info("mathod={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //类方法
        logger.info("class_method{}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        //参数
        logger.info("args={}",joinPoint.getArgs());
    }

后置通知 @After(“poincut()”)

  @After("poincut()")
    public void after(){
        logger.info("after");
    }

返回时通知 @AfterReturning(pointcut = “poincut()”,returning = “object”) returning指定返回对象。

 @AfterReturning(pointcut = "poincut()",returning = "object")
    public void afterReturning(Object object){
        logger.info("return = {}",object.toString());
//        logger.info("return = ");
    }

抛出异常时通知 @AfterThrowing(“poincut()”)

  @AfterThrowing("poincut()")
    public void afterThrowing(){
        logger.info("抛出异常了。");
    }

环绕通知 @Around(“poincut()”)

 @Around("poincut()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("环绕通知。");
        joinPoint.proceed();
    }



三。细节

(1)
@AfterReturning和 @Around(“poincut()”),,,会有特殊冲突,,搞了半天

SpringBoot中会出现空指针异常

Spring中启动时会出现错误无法启动,错误代码如下:解决方法(注释掉,@Around(“poincut()”))

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [G:\work_space\study_spring\spring_demo\target\classes\xatu\zsl\service\UserServiceImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut poincut
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [G:\work_space\study_spring\spring_demo\target\classes\xatu\zsl\service\UserServiceImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut poincut
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at xatu.zsl.MainTest.main(MainTest.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut poincut
    at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:301)
    at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:207)
    at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:193)
    at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:170)
    at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:220)
    at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:279)
    at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:311)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:88)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:347)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    ... 16 more

(2)JoinPoint joinPoint,参数不能出现在afterReturning(),,中,,不知道为什么,,容易出错,,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼠晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值