问题主要出在测试类
目标类
1 2 3 4
| public interface Target {
void fun(); }
|
1 2 3 4 5 6 7 8
| @Component public class TargetImpl implements Target{
@Override public void fun(){ System.out.println("执行方法"); } }
|
切面类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Component("DoAOP") @Aspect public class DoAOP {
@Pointcut("execution(* com.example.leetcode.aop..*(..))") public void pointcut(){ }
@Before("pointcut()") public void before(){ System.out.println("方法之前执行"); }
@Around("pointcut()") public void around(ProceedingJoinPoint joinPoint) throws Throwable { joinPoint.proceed(); }
}
|
测试类
这里要从IoC获取bean,我一开始自己new对象,发现怎么都不对,后来想到AOP是在bean的生命周期完成代理bean的替换,自己new不是代理类,自然无法用到那些增强的逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @SpringBootTest @RunWith(SpringRunner.class) @EnableAspectJAutoProxy @ComponentScan(basePackages = "com.example.leetcode.aop") public class AOPTest implements ApplicationContextAware {
ApplicationContext applicationContext;
@Test public void test(){ Target target = applicationContext.getBean(TargetImpl.class); target.fun(); }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
|