目标接口和目标类
package com.itliu.anno;
public interface TargetInterface {
public void save();
}
package com.itliu.anno;
import org.springframework.stereotype.Component;
@Component("target")
public class Target implements TargetInterface {
public void save() {
System.out.println("打印Target");
}
}
切面类
package com.itliu.anno;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component("myAespect")
@Aspect//标注当前类是一个切面
public class MyAespect {
// 定义切点表达式
@Pointcut("execution(public void com.itliu.anno.Target.*(..))")
public void pointcut(){}
// 配置前置通知
@Before("pointcut()")
public void before() {
System.out.println("前置增强");
}
// 配置后置通知
@After("pointcut()")
public void after() {
System.out.println("后置增强");
}
// 配置环绕通知
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前增强");
Object proceed = joinPoint.proceed();//切点方法
System.out.println("环绕后增强");
return proceed;
}
}
配置文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 组件扫描-->
<context:component-scan base-package="com.itliu.anno"></context:component-scan>
<!--AOP自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>