1:pom.xml中添加spring-boot-starter-aop。存在一个类,其中有一个sayhi()方法:
public String sayhi()
{
return "Testscanxml say hi";
}
2:切点(@Pointcut及切面(@Aspect)和通知(@Before/@Around)
public class NamePointCut {
/***
* 切点被命名为methon2,且该切点只能在本类中使用(因为切点定义的时候用的是private)(切点表达式很重要,要弄明白)
* 命名切点仅仅是为了方法名及访问修饰符,所以方法体为空且返回值为void类型
*/
@Pointcut(value = "execution(* sayhi(..))")
protected void methon2(){
}
}
@Configuration //当注释掉@Configuration这句(在没有@Component前提下),所有的AOP动作都不会执行了
@Aspect
@EnableAspectJAutoProxy //(proxyTargetClass = true)如果==true强制使用cglib
//@ComponentScan(basePackages = "com.example.javafxminademo") 有@Configuration,这句和下句都可以不需要
//@Component
public class NamePointCutAspect {
//切面类中使用切点,并且要说明是哪个切点(包括是哪个切点类的哪个切点方法)
@Before("NamePointCut.methon2()")
public void aspectMethon1(JoinPoint joinPoint)
{
System.out.println("NamePointCutAspect.aspectMethon1");
}
@Around("NamePointCut.methon2()")
public Object aspectAroundMethon(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("获取连接点对象开始");
System.out.println("对象"+proceedingJoinPoint.getTarget().getClass());
// System.out.println("参数"+proceedingJoinPoint.getArgs()[0]);//sayhi()无参,加上这句则异常
Object o = proceedingJoinPoint.proceed(); //将sayhi()的返回值返回
System.out.println("获取连接点对象结束");
return o;
}
}
3) System.out.println("sahi value="+testscanxml.sayhi());则显示如下:
获取连接点对象开始
对象class com.example.javafxminademo.Testscanxml
NamePointCutAspect.aspectMethon1
获取连接点对象结束
sahi value=Testscanxml say hi
4)如果切面类中不将proceedingJoinPoint.proceed()的返回值return的话,那么显示如下:
获取连接点对象开始
对象class com.example.javafxminademo.Testscanxml
NamePointCutAspect.aspectMethon1
获取连接点对象结束
sahi value=null
来源:oschina
链接:https://my.oschina.net/u/2963604/blog/3160196