我在application-context.xml中定义了一个Aspect及其配置,如下所示:
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="myAspect" class="myAspectClass"/>
<aop:config>
<aop:aspect ref="myAspect">
<aop:pointcut id="myPointCut" expression="(@within(MyPointCutAnnotation) or @annotation(MyPointCutAnnotation)) and execution(* *(..))"/>
<aop:before pointcut-ref="myPointCut" method="beforeMethod" />
</aop:aspect>
</aop:config>
我的servlet-context.xml看起来像这样:
<context:annotation-config />
<context:component-scan base-package="mypackage" />
我的Spring Controller类:
@Controller
@RequestMapping( value="/xxx", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE )
public class MyController {
@MyPointCutAnnotation
@ResponseBody
@RequestMapping( value="/signOn" )
public void myMethod() {
...do something
}
}
web.xml如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
但myPointCut不会被myMethod触发,除非我在servlet-context.xml中添加以下内容(导入根上下文),如下所示:
<import resource="classpath:application-context.xml"/ >
有人能告诉我为什么会这样吗?是不是所有bean都包括Aspect,PointCut和Advice在Spring中通过上下文层次结构自动在Controller中可用?
答案 0 :(得分:0)
将此代码添加到您的pom中。可能是你的问题可以解决。
<properties>
<aspectj.version>1.7.4</aspectj.version>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<outxml>true</outxml>
<complianceLevel>${java.version}</complianceLevel>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>