导入jar包
aopaliance.jar
aspectjweaver.jar
1编写类实现MethodBeforeAdvice接口
例:前置通知
public class Addbefore implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("前置通知!!");
}
}
2在配置文件中配置
2.1加入前置通知所在类
<bean id="addbefore" class="com.Spring.Addbefore" >
</bean>
2.2配置
<aop:config>
<aop:pointcut expression="execution(public void com.Spring.Student.add())" id="pointcut"/>
<aop:advisor advice-ref="addbefore" pointcut-ref="pointcut" />
</aop:config>
其中<aop:pointcut expression=“execution(public void com.Spring.Student.add())” id=“pointcut”/>为所要添加前置通知的方法
(其他通知配置相同)
后置通知
public class Addafter implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("后置通知!!!");
}
}
异常通知
public class Addexception implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] args,Object target, Throwable e) {
System.out.println("异常通知!!!");
}
}
环绕通知
public class Addaround implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = null;
try {
System.out.println("环绕前置通知");
result = invocation.proceed();
System.out.println("环绕后置通知");
}catch(Exception e) {
System.out.println("环绕异常通知");
}
return result;
}
}