1.导入相关jar包
commons-logging-1.1.1.jar
spring-aop-4.3.9.RELEASE.jar
spring-beans-4.3.9.RELEASE.jar
spring-context-4.3.9.RELEASE.jar
spring-core-4.3.9.RELEASE.jar
spring-expression-4.3.9.RELEASE.jar
aopalliance-1.0.jar
aspectjweaver-1.5.3.jar
2.切点的实现以及注入IOC容器(实现代码就不显示了)
在xml中配置:
<bean id="student" class="org.aop.Object.Student">
</bean>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(public void org.aop.Object.Student.display())" id="pointcut"/>
</aop:config>
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
3.通知类实现
注意:
@Aspect //声明该类是一个通知
@Before //前置通知注解
@AfterReturning //后置通知注解
@AfterThrowing //异常通知注解
@Around //环绕通知注解
@After //最终通知注解
@Component("advice")
@Aspect //声明该类是一个通知
public class Advice {
@Before("execution( public void org.aop.Object.Student.display())") //定义切点
public void before(JoinPoint p)
{
System.out.println("前置通知!"+"目标对象:"+p.getTarget()+"方法名: "
+p.getSignature().getName()+"参数个数:"+p.getArgs().length);
}
@AfterReturning(pointcut="execution( public void org.aop.Object.Student.display())",returning="returningValue")
public void after(JoinPoint p,Object returningValue) //声明返回值的参数名
{
System.out.println("后置通知!"+returningValue);
}
@AfterThrowing("execution( public void org.aop.Object.Student.display())")
public void exception()
{
System.out.println("异常通知!");
}
@Around("execution( public void org.aop.Object.Student.display())")
public void around(ProceedingJoinPoint p )
{
Object result=null;
try {
System.out.println("环绕通知实现的前置通知!");
result=p.proceed();
System.out.println("环绕通知实现的后置通知!");
}
catch(Throwable e)
{
System.out.println("环绕通知实现的异常通知!");
}
finally {
System.out.println("环绕通知实现的最终通知!");
}
}
@After("execution( public void org.aop.Object.Student.display())")
public void fianlly()
{
System.out.println("最终通知!");
}
通过注解形式 实现的aop如果想获取 目标对象的一些参数,则需要使用一个对象:JointPoint,而在环绕通知中使用ProceedingJoinPoint。
注解形式的返回值的参数名:一定要声明返回值参数名,否则无法运行
@AfterReturning(pointcut="execution( public void org.aop.Object.Student.display())",returning="returningValue")
public void after(JoinPoint p,Object returningValue) //声明返回值的参数名
4.继续配置xml
<context:component-scan base-package="org.aop.Log"></context:component-scan>
<!--配置扫描器将通知类注入IOC容器 -->
<aop:aspectj-autoproxy> <!-- 开启注解对AOP的支持 -->
</aop:aspectj-autoproxy>
5.运行