Spring @EnableAspectJAutoProxy 典型用法

典型用法

第1步:定义切面类(Aspect)

使用 @Aspect 注解标记一个类为切面类,并结合 @Component 或 @Service 注册为 Spring Bean。

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    // 定义切点:拦截 com.example.service 包下所有方法
    @Before("execution(* com.example.service.*.*(..))")
    public void logMethodCall() {
        System.out.println("【AOP】方法开始执行...");
    }
}

第2步:启用 AspectJ 自动代理

XML 配置方式(适用于传统 Spring 项目)

如果你使用的是 XML 配置方式,可以这样启用 AspectJ 自动代理

<aop:aspectj-autoproxy />

<beans xmlns="http://www.springframework.org/schema/beans"
       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/aop 
           http://www.springframework.org/schema/aop/spring-aop.xsd">

Java 注解配置方式(适用于 Spring 项目)

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}

@EnableAspectJAutoProxy(proxyTargetClass = true) // true:强制使用 CGLIB 代理(默认为 JDK 动态代理)。

Spring Boot 方式(最简化)

只需添加依赖,并将切面类标注为 @Aspect + @Component,即可自动生效。不需要手动添加 @EnableAspectJAutoProxy。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值