Spring4 AOP配置,在不同的XML里,不产生作用,为什么?
l932 2016-03-10 02:25:27 先介绍一下背景,我接手的是一个SpringMVC+Spring(4.1.7)+MyBatis(3.3.0)的项目。
原来配置这一套的程序员,搞了两个xml:spring-context.xml和spring-mvc.xml。
【我扩展了一个xml,在spring-context.xml中使用<import/>导入——这一段代码跟本次问题没有关系。】
在web.xml中是这么配置的(关键代码):
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
......
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
后来,我需要添加一个功能,需要用到AOP,准备采用注解的方法来搞,看网上的教程,第一步都是要在xml里配置:
<aop:aspectj-autoproxy/>
有的还要求配置成:
<aop:aspectj-autoproxy proxy-target-class="true"/>
这里面主要是告诉Spring使用CGLIB还是JDK动态代理,CGLIB代理是不能面向接口编程的,设置为true就是用CGLIB。
所以我在使用AOP的时候直接用了<aop:aspectj-autoproxy/>。
不好意思上面啰嗦了半天,下面进入正题:
之前的程序员在xml里面是配置了<aop:aspectj-autoproxy/>的,是配置在spring-mvc.xml里,我在开发的时候,只是瞄了一眼,看xml里有这个配置我就没有在意了,开始开发AOP的相关程序,但是无论我怎么做,写的AOP都不起作用,最后我忘了是看哪个教程了,把<aop:aspectj-autoproxy/>这段配置从spring-mvc.xml挪到了spring-context.xml里,AOP的程序立马起作用了!
我的问题就是:
<aop:aspectj-autoproxy/>这段配置为什么在spring-mvc.xml里不起作用,在spring-context.xml里就起作用?