记一次基于xml配置的springMvc自定义aop切面增强controller

    科技2022-08-31  102

    aop代码

    @Aspect @Component("wySystemErrorAdvice") public class WySystemErrorAdvice { @Autowired @Qualifier(WebExecptionResolver.beanid) private WebExecptionResolver webExecptionResolver; /** * 定义一个切点 此处去除了项目实际中使用的切点 **/ @Pointcut("execution(* ") public void pointCut() { } @AfterThrowing(value = "pointCut()", throwing = "ex") public void afterThrowing(JoinPoint jp, Exception ex) { Object[] args = jp.getArgs(); HttpServletRequest request = (HttpServletRequest) args[0]; HttpServletResponse response = (HttpServletResponse) args[1]; WyWebExceptionResolver.holder.getIfAbsent("APP"); try{ // 使用自定义的异常处理机制处理 webExecptionResolver.resolve(request, response, ex); }catch (Exception e){ e.printStackTrace(); } } }

    aop 配置

    需要注意的是springMvc中使用的是父子容器,所以需要在applicationContext-springMvcConfig.xml中添加,而不是在applicationContext-server.xml中,这一点很重要

    <!-- 打开注解支持--> <context:annotation-config/> <!-- 扫描插件包内的监控模块 --> <context:component-scan base-package="aop切面类的包名"/> <!-- 激活自动代理功能 --> <aop:aspectj-autoproxy proxy-target-class="true"/>

    如何确定自己的切面类已经加载到了spring容器中

    了解过spring源码的应该对AbstractApplicationContext中的refresh很熟悉,找到这个方法,我们在finishBeanFactoryInitialization(beanFactory);这行打一个断点,当程序允许到此处执行beanFactory.getBeanDefinition(‘切面的beanId’) 如果能够获取到对象则说明切面类已经被容器加载,需要注意一点,如果该切面类注入到了springIoc中,也就是springMvc的父容器中,那么此处也可以拿到切面对象,但是controller并不会得到增强

    总结

    springAop 用起来还是很方便的,编写切面代码对原有功能的侵扰性很低,可以实现插拔式插件,灵活开启关闭。

    缺点: 调试起来很麻烦,第一次配置的时候因为aop切面类没有被spring加载而纠结很久,需要耐下心来查找原因。

    Processed: 0.008, SQL: 9