Spring AOP ANNOTATION 不起作用的问题
问题介绍
1 在Spring配置文件中定义了
<aop:aspectj-autoproxy/>
<context:component-scan base-package="demo">
<context:include-filter type="annotation"
expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>2 MyAspect.java 代码
package demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
public class MyAspect {
@Around("execution(* demo.*.*(..))")
public void m1(ProceedingJoinPoint jp) throws Throwable {
System.out.println(jp.getThis().getClass().getName());
System.out.println(jp.getTarget().getClass().getName());
if(jp.getTarget().getClass() == HelloWorldB.class){
System.out.println("HelloWorldB return");
}else{
System.out.println("HelloWorldA proceed");
jp.proceed(jp.getArgs());
}
}
}
3 但是aspect就是不起作用annotation有了 自动发现bean有了 启用aspectj有了后来发现因为aspect缺少<span style="font-family: Arial, Helvetica, sans-serif;">@Component标注</span><pre name="code" class="java">导致spring没发现这个bean所以就不能自动化加载了如果不用bean自动加载,就需要明确在配置文件中定义这个aspect
正确代码
package demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around("execution(* demo.*.*(..))")
public void m1(ProceedingJoinPoint jp) throws Throwable {
System.out.println(jp.getThis().getClass().getName());
System.out.println(jp.getTarget().getClass().getName());
if(jp.getTarget().getClass() == HelloWorldB.class){
System.out.println("HelloWorldB return");
}else{
System.out.println("HelloWorldA proceed");
jp.proceed(jp.getArgs());
}
}
}
本文深入探讨了在Spring配置中使用AOP Annotation时遇到的问题,特别是当aspect缺少@Component标注导致无法正常加载的情况。通过示例代码解释了问题原因,并提供了正确的实现方式以确保AOP功能正常工作。
4531

被折叠的 条评论
为什么被折叠?



