配置文件的写法
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>
<bean id="Interceptor" class="com.sszd.aop.DbManage"/>
<bean id="DBBean" class="com.sszd.db.DbOpretor"/>
</beans>
首先编写一个方法类
package com.sszd.db;
public class DbOpretor {
public void insert(String sql)//带参数
{
System.out.println("insert方法(带参数)");
}
public int select(int id)//带返回值
{
System.out.println("select方法(有返回值)");
return id;
}
public void commit()
{
System.out.println("commit方法");
}
}
创建一个切面类
@Aspect
public class DbManage {
@Pointcut("execution(* com.sszd.db..*.*(..))")
public void perform(){}
@Before("perform()")
public void preMangeNoargs()
{
System.out.println("前置通知无参数");
}
@AfterReturning("perform()")//无返参数
public void afterMange()
{
System.out.println("后置通知无参数");
}
}
我这里用Junit做测试
package com.sszd.test;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sszd.db.DbOpretor;
public class AOPTest extends TestCase {
public void testAop()
{
ApplicationContext cxt = new ClassPathXmlApplicationContext("ApplicationContext.xml");
DbOpretor db = (DbOpretor)cxt.getBean("DBBean");
db.commit();
}
}
此外还可以对有参数以及有返回值的方法进行拦截
如insert方法
对比上一个DbManage类
@Aspect
public class DbManage {
@Pointcut("execution(* com.sszd.db..*.*(..))")
public void perform(){}
@Before("perform() && args(sql)")//带参数
public void preMangeArgs(String sql)
{
System.out.println("前置通知带参数");
System.out.println("DbManage中接收的SQL:"+sql);
}
@AfterReturning(pointcut="perform()",returning="result")//有返回值
public void afterMange(int result)
{
System.out.println("后置通知");
System.out.println("DbOpretor->select方法返回原值:"+result+"/n");
}
}
继续Junit测试:
package com.sszd.test;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sszd.db.DbOpretor;
public class AOPTest extends TestCase {
public void testAop()
{
ApplicationContext cxt = new ClassPathXmlApplicationContext("ApplicationContext.xml");
DbOpretor db = (DbOpretor)cxt.getBean("DBBean");
//db.commit();
db.insert("insert SQL");
db.select(2);
}
}
运行它: