您的位置:首页 > 编程语言 > Java开发

解决spring aop xml配置无效的问题

2019-01-28 16:44 369 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yj1499945/article/details/86679432

web.xml

[code]<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,classpath:applicationContext2.xml,classpath:applicationContextAspect.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

applicationContextAspect.xml

[code]    <!-- 2 切面类(多个通知) -->
<bean id="myAspect1" class="aspectxml.MyAspect"></bean>

<aop:config>
<aop:aspect ref="myAspect1">
<!-- 3.2 配置切入点 -->
<aop:pointcut expression="execution(* controller..TestController.*(..))" id="myPonitCut"/>
<!--3.3 声明通知类型-->
<!--#1 前置通知 , 目标方法之前执行。-->
<!--* 第一个参数为JoinPoint,可以获得目标方法名等。-->
<aop:before method="myBefore" pointcut-ref="myPonitCut"/>
<!--#2 后置通知,目标方法之后执行,可以获得返回值。 通过“returning”属性配置第二个参数的名称,获得返回值的,类型必须Object-->
<!--* 第一个参数为:JoinPoint-->
<!--* 第二个参数为:Object xxx-->
<aop:after-returning method="myAfterReturning" pointcut-ref="myPonitCut" returning="xxx"/>
<!--#3 环绕通知, 目标方法前后-->
<!--方法要求:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{-->
<!--执行目标方法:joinPoint.proceed();-->
<aop:around method="myAround" pointcut-ref="myPonitCut"/>
<!--#4 抛出异常通知,目标方法出现异常时才执行。通过“throwing”属性配置第二个参数的名称,获得具体的异常信息,类型必须是Throwable-->
<!--* 第一个参数为:JoinPoint-->
<!--* 第二个参数为:Throwable e-->
<aop:after-throwing method="myAfterThrowing" pointcut-ref="myPonitCut" throwing="e"/>

</aop:aspect>

</aop:config>

看上去好像没什么问题,其实问题来自于你对上下文的理解程度。servlet初始化用于DispatcherServlet,而ContextLoaderListener初始化webapplicationcontext。webapplicationcontext是DispatcherServlet的父容器。子容器可以获取父容器的bean,反过来不行。所以这个问题就很好理解了。在aop的bean中,无法获取切入点的bean所以无效。正确的解决方法就是把这个配置放到applicationContext-mvc.xml中。解决问题。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: