一个 AOP 的简单例子,用作源码触发入口

2025/05/20

AopTest.java

public class AopTest {

    @Test
    public void testAop() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class);

        // 获取代理对象
        DemoService demoService = context.getBean(DemoService.class);

        // 触发切面方法
        demoService.save();

        context.close();
    }
}

Application.java

@Configuration
@ComponentScan("mine.projects.aopdemo_cglib")
@EnableAspectJAutoProxy(proxyTargetClass = false)
public class Application {
}

DemoService.java

@Service
public class DemoService {
    public void save() {
        System.out.println("Save run");
    }
}

ServiceAspect.java

@Aspect
@Component
public class ServiceAspect {
    @Before("execution(public * mine.projects.aopdemo_cglib.DemoService.*(..))")
    public void beforePrint() {
        System.out.println("before run...");
    }
}

执行结果:

建议在空方法上声明切点,并通过空方法引用这些切点。

ServiceAspect.java 的优化写法:

@Aspect
@Component
public class ServiceAspect {
 @Pointcut("execution(* mine.archive.aop.aopdemo_jdk.DemoService.*(..))")
 public void pointCut() {}

 @Before("pointCut()")
 public void beforePrint() {
  System.out.println("before run...");
 }
}