这个例子使用之前Spring—spring mvc框架入门的例子。当然你也可以用自己的。
1、因为要使用到@Aspect来标注这个类是一个用于设置关注方面的类(切面类...),所以需要相应的jar文件。相应的文件在我的资源中有,名字叫做aspectj-1.7.0.jar,压缩包里面有个Libs目录中有相应的jar文件,*tool的那个jar可以不用加入。另外还需要一个实现拦截器的类,涉及到的包是com.springsource.org.aopalliance-1.0.0.jar(这个是Spring Aop框架指定要的,对于单独的aspectj来说不需要),这个也在我的资源里面。所以最终需要另外加入的库有4个:
com.springsource.org.aopalliance-1.0.0.jar
aspectjrt.jar
aspectjweaver.jar
org.aspectj.matcher.jar
2、首先我们创建一个类,代码如下:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class SystemArchitecture {
@Pointcut("within(xyz.sample.baremvc.*Controller)")
public void testController(){
}
@Before("testController()")
public void testAdvice()
{
System.out.println("Hello AOP world");
}
}
这个地方有几点注意的:
1、我们加入@Component,这个希望的是在Spring进行组件扫描的时候能自动的把我们这个类也扫描进去,因为@Aspect不是属于@Component(不像@Service、@Controller这些一样),所以需要加入@Component。
2、@Pointcut指示了我们感兴趣的类及方法,这里我们感兴趣的类是xyz.sample.baremvc这个包下面(within表示指定感兴趣的类型),并且类的结尾是Controller的那些类,因此就指定了我们感兴趣的类是HomeController这个类,而其他的如AppConfig、CaseInsensitiveComparator等这些类就不包括在内了;PointCut可以针对类也可以针对方法,也可以针对方法的参数等等,这个因为Pointcut是AOP的核心部分,所以比较复杂,后面在考虑各种例子,这里暂时不考虑这些。还有一点注意的是@Pointcut标注后面的函数只是相当于一个标示,用于被Advice所引用。
3、@Before指示了我们的建议的类型,就是所做的动作是发生在Join point之前的(“Before”),后面的testController()表示了对应的动作是针对那些Join point,这个其实是我们上面定义好的,就是HomeController类里面的那些方法,这里就是有两个一个是: home(),另一个是public String compare(..)。
所以上面的这个Aspect就是增加了对HomeController的关注,当HomeController执行各种类方法的时候,这个Aspect会执行定义好的Advice,这个Advice是一个Before类型的Advice,所以会在执行HomeController的类方法前执行,所以当在浏览器地址栏中输入:http://localhost:8080/baremvc
后,在Console上面输出的是:
Hello AOP world
HomeController: Passing through...
3、需要在Spring的上下文中加入一个Aspect代理下面是代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<context:component-scan base-package="yuxd.sample" ></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="WEB-INF/views/"></property>
</bean>
<aop:aspectj-autoproxy/>
</beans>
这里就是多加了个<aop:aspectj-autoproxy/>,这样可以让标注了@Aspect的类自动的代理关注的那些类(被切到的那些类)
例子很简单吧?有问题可以留言