首先,需要的包如下图所示
然后,编辑Interceptor:
package com.yrsoft.service;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* 切面
*/
@Aspect
public class MyInterceptor {
/**
* 第一个星号为返回值类型,*为any
* 后面是包名。包名后面的两个点代表对该包下的子包也进行拦截
*点后面的星号是类名,对哪个类进行拦截。
*第三个星号为方法,方法后的括号代表任意参数,有或者没有都行
* 其实就是一个方法不带访问修饰符的声明
*/
@Pointcut("execution(* com.yrsoft.service.impl.PersonServiceBean.*(..))")
private void anyMethod(){}//这里不是定义方法,而是定义切入点名称
@Before("anyMethod()")//执行anyMethod之前先执行这个前置通知
public void doAccessCheck(){
System.out.println("前置通知");
}
}
编辑一个要切入的类(接口略)
package com.yrsoft.service.impl;
import com.yrsoft.service.PersonService;
public class PersonServiceBean implements PersonService {
@Override
public void save(String name) {
System.out.println("save() --> " + name);
}
@Override
public void update(String name, Integer id) {
System.out.println("update () ");
}
@Override
public String getPersonName(String name, Integer id) {
return "xxx";
}
}
编辑测试类
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yrsoft.service.PersonService;
public class SpringAOPTest {
@Test
public void interceptorTest() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService service = (PersonService) ctx.getBean("personService");
service.save("123");
}
}
编辑spring的applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<aop:aspectj-autoproxy/>
<bean id="myInterceptor" class = "com.yrsoft.service.MyInterceptor"/>
<bean id = "personService" class = "com.yrsoft.service.impl.PersonServiceBean"/>
</beans>
xml说明:
beans节点中需要加入
xmlns:aop="http://www.springframework.org/schema/aop"
以及
xsi:schemaLocation="<span style="font-family: Arial, Helvetica, sans-serif;">http://www.springframework.org/schema/aop </span><span style="font-family: Arial, Helvetica, sans-serif;">http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"</span>
而
<aop:aspectj-autoproxy/>
是用来加入动态代理的。
最后测试会先输出前置通知然后输出save() --> 123才是正确的结果。
ps:如果遇见java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut anymethod 是因为aspectjweaver.jar版本不对,更新一下就行了。我遇到这个问题从1.6.2更新到1.6.12就解决了