首先我们编写接口:
package com.shizhan.inter;
public interface Teach {
public void teach(String name);
}
接口实现类:
package com.shizhan.impl;
import com.shizhan.inter.Teach;
public class TeachImpl implements Teach{
@Override
public void teach(String name) {
System.out.println("开始上课了");
}
}
前置通知:
package com.shizhan.impl;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class PrepareLesson implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] objects, Object object)
throws Throwable {
System.out.println("预习功课");
}
}
后置通知:
package com.shizhan.impl;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class Review implements AfterReturningAdvice{
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("复习功课");
}
}
环绕通知:
package com.shizhan.impl;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class Teaching implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("开始teach");
//调用下一个MethodInterceptor,如果没有则调用目标对象的方法
invocation.proceed();
System.out.println("结束teach");
return null;
}
}
异常通知:
package com.shizhan.impl;
import org.springframework.aop.ThrowsAdvice;
public class TeachException implements ThrowsAdvice{
public void afterThrowing(Exception e){
System.out.println(e);
System.out.println("异常来了");
}
public void afterThrowing(NullPointerException e){
System.out.println(e);
System.out.println("ExceptionInterceptor NullPointerException");
}
}
配置AOP:
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<!-- 目标对象 -->
<bean id="teach" class="com.shizhan.impl.TeachImpl"/>
<!-- 前置通知 -->
<bean id="prepareLesson" class="com.shizhan.impl.PrepareLesson"/>
<!-- 后置通知 -->
<bean id="review" class="com.shizhan.impl.Review"/>
<!-- 环绕通知 -->
<bean id="teaching" class="com.shizhan.impl.Teaching"/>
<!-- 异常通知 -->
<bean id="teachexception" class="com.shizhan.impl.TeachException"/>
<!-- 定义代理对象 -->
<bean id="teachProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 接口 -->
<property name="proxyInterfaces">
<value>com.shizhan.inter.Teach</value>
</property>
<!-- 通知 -->
<property name="interceptorNames">
<list>
<value>teachexception</value>
<value>prepareLesson</value>
<value>review</value>
<value>teaching</value>
</list>
</property>
<!-- 目标对象 -->
<property name="target">
<ref bean="teach"></ref>
</property>
</bean>
</beans>