public class MyAspect {
public void beforeAdvice(JoinPoint jp){
//调用目标对象时,所传递的调用参数,都会在advice中被JoinPoint所拦截
System.out.println("执行之前。。");
Object[] args = jp.getArgs();
if(args!=null){
for(Object obj : args){
System.out.println(obj);
}
}
System.out.println("执行之前结束。。。");
}
public void afterAdvice(){
System.out.println("执行之后。。");
}
public void afterReturningAdvice(){
System.out.println("执行之后(返回值)..");
}
public void afterThrowingAdvice(){
System.out.println("执行时抛异常。。");
}
//环绕通知(interceptor)
public Object doRoundIntercept(ProceedingJoinPoint pjp)throws Throwable{
System.out.println("环绕开始。。");
Object result = null;
try {
result = pjp.proceed();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("环绕结束。。");
return result;
}
}
public class LoginDAO {
public boolean validate(String username,String password){
System.out.println("执行了 LoginDAO...validate()");
// if(true){
// throw new RuntimeException("我爱异常。。");
// }
return true;
}
}
public class SpringAOPTest {
private static ClassPathXmlApplicationContext ctx;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ctx = new ClassPathXmlApplicationContext("beans.xml");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
if(ctx!=null){
ctx.close();
}
}
@Test
public void testAOP(){
LoginDAO loginDAO = (LoginDAO)ctx.getBean("loginDAO");
loginDAO.validate("aaa", "111");
}
}
<?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-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd "> <!-- 把LoginDAO纳入spring IoC容器管理 --> <bean id="loginDAO" class="com.dao.LoginDAO"/> <!-- 定义一个切面(aspect) --> <bean id="myAspect" class="com.aspect.MyAspect"/> <!-- 把切面(里面的通知)织入到目标对象--> <aop:config > <aop:aspect id="asp" ref="myAspect"> <!-- 定义一个切入点(告诉切面asp,应该把里面的通知织入到哪个类中哪个方法中) --> <aop:pointcut id="myPointcut" expression="execution (* com.mypack.dao..*.*(..))"/> <aop:after method="afterAdvice" pointcut-ref="myPointcut"/> <aop:after-returning method="afterReturningAdvice" pointcut-ref="myPointcut"/> <aop:after-throwing method="afterThrowingAdvice" pointcut-ref="myPointcut"/> <aop:before method="beforeAdvice" pointcut-ref="myPointcut"/> <aop:around method="doRoundIntercept" pointcut-ref="myPointcut"/> </aop:aspect> </aop:config> </beans>