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&#61;"aop切面类的包名"/><aop:aspectj-autoproxy proxy-target-class&#61;"true"/>
如何确定自己的切面类已经加载到了spring容器中
了解过spring源码的应该对AbstractApplicationContext中的refresh很熟悉&#xff0c;找到这个方法&#xff0c;我们在finishBeanFactoryInitialization(beanFactory);这行打一个断点&#xff0c;当程序允许到此处执行beanFactory.getBeanDefinition(‘切面的beanId’) 如果能够获取到对象则说明切面类已经被容器加载&#xff0c;需要注意一点&#xff0c;如果该切面类注入到了springIoc中&#xff0c;也就是springMvc的父容器中&#xff0c;那么此处也可以拿到切面对象&#xff0c;但是controller并不会得到增强
总结
springAop 用起来还是很方便的&#xff0c;编写切面代码对原有功能的侵扰性很低&#xff0c;可以实现插拔式插件&#xff0c;灵活开启关闭。
缺点&#xff1a;
调试起来很麻烦&#xff0c;第一次配置的时候因为aop切面类没有被spring加载而纠结很久&#xff0c;需要耐下心来查找原因。