使用Spring AOP 拦截 方法,给被拦截的方法加上,前置通知,后置通知,例外通知,最终通知 的两个例子,见 附件
需要 spring.jar,cglib.jar,commons-logging.jar
方式1. 被拦截的类没有实现任何接口
关键代码:
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import cn.com.xinli.common.BusinessMethodInterceptor;
import cn.com.xinli.service.BusinessInterface;
import cn.com.xinli.service.impl.BusinessImpl;
/*springAOP 测试方式1 的测试用例 只需要spring.jar 支持
*
* */
public class AOPTest
{
static BusinessInterface face=null;
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
BusinessImpl bi=new BusinessImpl();
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTarget(bi);
proxyFactoryBean.addAdvisor(new DefaultPointcutAdvisor(new BusinessMethodInterceptor()));
proxyFactoryBean.setInterfaces(new Class[]{BusinessInterface.class});
face= (BusinessInterface)proxyFactoryBean.getObject();
}
@Test
public void testAdd() throws Exception
{
face.add();
}
@Test
public void testDel()
{
face.del();
}
@Test
public void testFind()
{
face.find();
}
@Test
public void testUpdate()
{
face.update();
}
}
方式2. 被拦截的类没有实现任何接口
关键代码:
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import cn.com.xinli.common.BusinessMethodInterceptor;
import cn.com.xinli.service.impl.Business;
/*springAOP 测试方式2 的测试用例 需要spring.jar和cglib.jar 支持
*
* */
public class AOPTest2
{
static Business business =null;
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
/**/
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.addAdvisor(new DefaultPointcutAdvisor( new BusinessMethodInterceptor()));
proxyFactoryBean.setTarget(new Business());
business = (Business) proxyFactoryBean.getObject();
}
@Test
public void testAdd() throws Exception
{
/*另一种调用方式*/
Business target = new Business();
ProxyFactory pf = new ProxyFactory();
pf.addAdvice(new BusinessMethodInterceptor());
pf.setTarget(target);
Business proxy = (Business) pf.getProxy();
//输出代理对象调用的信息
proxy.add();
}
@Test
public void testDel()
{
business.del();
}
@Test
public void testFind()
{
business.find();
}
@Test
public void testUpdate()
{
business.update();
}
}
参考:
http://blog.csdn.net/Jyeafee/archive/2006/01/11/575972.aspx