8.AspectJ对AOP的实现(重点)

本文详细介绍了AspectJ在Spring框架中实现AOP(面向切面编程)的方法,包括AspectJ的基本概念、通知类型、切入点表达式以及如何在Spring环境中进行配置。通过示例展示了基于注解和XML的两种AOP实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AspectJ实现了AOP的功能,且实现方式更为简洁,使用更为方便,而且还支持注解式开发
在Spring中使用AOP开发时,一般使用AspectJ的实现方式


一、AspectJ简介

AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守java字节码规范的Class文件。


二、AspectJ的通知类型

AspectJ中常用的通知有五种类型:

  1. 前置通知
  2. 后置通知
  3. 环绕通知
  4. 异常通知
  5. 最终通知:无论程序执行是否正常,该通知都会执行。类似于try…catch中的finally代码块。

三、AspectJ的切入点表达式

AspectJ除了提供了5种通知外,还定义了专门的表达式用于指定切入点。表达式的原型是:

execution([modifiers-pattern] 访问权限类型
ret-type-pattern 返回值类型
[declaring-type-pattern 全限定性类名
name-pattern(param-pattern) 方法名(参数名)
[throws-pattern] 抛出异常类型)

切入点表达式要匹配的对象就是目标方法的方法名。所以execution表达式中明显就是方法的签名。注意,表达式中加[]的部分表示可省略部分,各部分间用空格分开。在其中可以使用以下符号:

符号意义
*0至多个任意字符
. .用在方法参数中,表示任意多个参数/用在包名后,表示当前包及其子包路径
+用在类名后,表示当前类及其子类/用在接口后,表示当前接口及其实现类

例:
execution(public * * (. .))
指定切入点为:任意公共方法

execution(* set * (. .))
指定切入名为:任何一个以“set”开始的方法

execution(* com.xyz.service. * . * (. .))
指定切入名为:定义在service包里的任意类的任意方法

execution(* com.xyz.service. . * . * (. .))
指定切入点为:定义在service包或者子包里的任意类的任意方法。". ."出现在类名中时,后面必须跟“ * ”,表示包、子包下的所有类

execution(* *.service. * . *(. .))
指定只有一级包下的service子包下所有类(接口)中所有方法为切入点

execution(* * . .service. * . * (. .)) 重点掌握
指定所有包下的service子包下所有类(接口)中所有方法为切入点

execution(* * . . ISomeService . * (. .)) 重点掌握
指定所有包下的ISomeService接口中所有方法为切入点


四、AspectJ的开发环境
  1. 导入jar包
    aopalliance.jar
    aspectjrt.jar
    aspectjweaver.jar
    spring-aop.jar
    spring-aspects.jar(spring与aspectj整合的jar包)

五、AspectJ基于注解的AOP实现
AspectJ提供了以注解方式对于AOP的实现

接口类

//主业务接口
public interface ISomeService {
    //目标方法
    void doFirst();

    //目标方法
    String doSecond();

    //目标方法
    void doThird();

}

实现类

public class SomeServiceImpl implements ISomeService {
    @Override
    public void doFirst() {
        System.out.println("执行doFirst()方法");
    }

    @Override
    public String doSecond() {
        System.out.println("执行doSecond()方法");
        return "abcde";
    }

    @Override
    public void doThird() {
        System.out.println("执行doThird()方法" + 3 / 0);
        System.out.println("执行doThird()方法");
    }
}

切面类

@Aspect //表示当前类为切面
public class MyAspect {

    @Before("execution(* *..ISomeService.doFirst(..))") //放入切入点表达式
    public void before() {
        System.out.println("执行前置通知方法");
    }

    @AfterReturning(value = "execution(* *..ISomeService.doSecond(..))",returning = "result")
    public void myAfterReturning(Object result){
        System.out.println("执行后置通知方法 result = " + result);
    }

    @Around("execution(* *..ISomeService.doSecond(..))")
    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("执行环绕通知方法,目标方法执行之前");
        //执行目标方法
        Object result = pjp.proceed();
        System.out.println("执行环绕通知方法,目标方法执行之后");
        if (result != null) {
            result = ((String)result).toUpperCase();
        }
        return result;
    }

    @AfterThrowing("execution(* *..ISomeService.doThird(..))")
    public void myAfterThrowing() {
        System.out.println("执行异常通知方法");
    }

    @AfterThrowing(value = "execution(* *..ISomeService.doThird(..))", throwing = "ex")
    public void myAfterThrowing(Exception ex) {
        System.out.println("执行异常通知方法 ex = " + ex.getMessage());
    }

    @After("doThirdPointcut()")
    public void myAfter() {
        System.out.println("执行最终通知方法");
    }

    //定义了一个切入点,叫doThirdPointcut()
    @Pointcut("execution(* *..ISomeService.doThird(..))")
    public void doThirdPointcut() {}
}

xml配置

	<!--注册切面-->
    <bean id="myAspect" class="com.chen.service.MyAspect"/>

    <!--注册目标对象-->
    <bean id="someService" class="com.chen.service.SomeServiceImpl"/>

    <!--注册AspectJ的自动代理-->
    <aop:aspectj-autoproxy/>

测试及结果

public class MyTest {
    @Test
    public void test01() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        ISomeService service = (ISomeService) ac.getBean("someService");
        service.doFirst();
        System.out.println("- - - - - -");
        service.doSecond();
        System.out.println("- - - - - -");
        service.doThird();
    }
}
/*
执行前置通知方法
执行doFirst()方法
- - - - - -
执行环绕通知方法,目标方法执行之前
执行doSecond()方法
执行环绕通知方法,目标方法执行之后
执行后置通知方法 result = ABCDE
- - - - - -
执行最终通知方法
执行异常通知方法
执行异常通知方法 ex = / by zero
*/

六、AspectJ基于xml的AOP实现(重点!!!)

切面类

public class MyAspect {

    public void before() {
        System.out.println("执行前置通知方法");
    }

    public void myAfterReturning(Object result){
        System.out.println("执行后置通知方法 result = " + result);
    }

    public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("执行环绕通知方法,目标方法执行之前");
        //执行目标方法
        Object result = pjp.proceed();
        System.out.println("执行环绕通知方法,目标方法执行之后");
        if (result != null) {
            result = ((String)result).toUpperCase();
        }
        return result;
    }

    public void myAfterThrowing() {
        System.out.println("执行异常通知方法");
    }

    public void myAfterThrowing(Exception ex) {
        System.out.println("执行异常通知方法 ex = " + ex.getMessage());
    }

    public void myAfter() {
        System.out.println("执行最终通知方法");
    }


}

xml配置

	<!--注册切面-->
    <bean id="myAspect" class="com.chen.service.MyAspect"/>

    <!--注册目标对象-->
    <bean id="someService" class="com.chen.service.SomeServiceImpl"/>

    <!--AOP配置-->
    <aop:config>
        <aop:pointcut id="doFirstPointcut" expression="execution(* *..ISomeService.doFirst(..))"/>
        <aop:pointcut id="doSecondPointcut" expression="execution(* *..ISomeService.doSecond(..))"/>
        <aop:pointcut id="doThirdPointcut" expression="execution(* *..ISomeService.doThird(..))"/>
        <aop:aspect ref="myAspect">
            <aop:before method="before" pointcut-ref="doFirstPointcut"/>
            <aop:after-returning method="myAfterReturning(java.lang.Object)" pointcut-ref="doSecondPointcut" returning="result"/>
            <aop:around method="myAround" pointcut-ref="doSecondPointcut"/>
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="doThirdPointcut"/>
            <aop:after-throwing method="myAfterThrowing(java.lang.Exception)" pointcut-ref="doThirdPointcut" throwing="ex"/>
            <aop:after method="myAfter" pointcut-ref="doThirdPointcut"/>
        </aop:aspect>
    </aop:config>

测试及结果

	@Test
    public void test01() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        ISomeService service = (ISomeService) ac.getBean("someService");
        service.doFirst();
        System.out.println("- - - - - -");
        service.doSecond();
        System.out.println("- - - - - -");
        service.doThird();
    }
    /*
	执行前置通知方法
	执行doFirst()方法
	- - - - - -
	执行环绕通知方法,目标方法执行之前
	执行doSecond()方法
	执行环绕通知方法,目标方法执行之后
	执行后置通知方法 result = ABCDE
	- - - - - -
	执行doThird()方法
	执行最终通知方法
	*/
2025-06-18 14:20:18.485 ERROR [] [http-nio-19008-exec-172] com.pmacsbackground.nbi.config.LogAspect - Illegal argument in method: sendAlarmClearToHiNMS cn.hutool.http.HttpException: Read timed out at cn.hutool.http.HttpResponse.init(HttpResponse.java:531) at cn.hutool.http.HttpResponse.initWithDisconnect(HttpResponse.java:504) at cn.hutool.http.HttpResponse.<init>(HttpResponse.java:82) at cn.hutool.http.HttpRequest.doExecute(HttpRequest.java:1183) at cn.hutool.http.HttpRequest.execute(HttpRequest.java:1050) at cn.hutool.http.HttpRequest.execute(HttpRequest.java:1026) at com.pmacsbackground.nbi.service.impl.AlarmClearMessageSendImpl.nmsAlarmClear(AlarmClearMessageSendImpl.java:610) at com.pmacsbackground.nbi.service.impl.AlarmClearMessageSendImpl.sendAlarmClearToHiNMS(AlarmClearMessageSendImpl.java:436) at com.pmacsbackground.nbi.controller.AlarmClearMessageSendController.sendAlarmClearToHiNMS(AlarmClearMessageSendController.java:38) at com.pmacsbackground.nbi.controller.AlarmClearMessageSendController$$FastClassBySpringCGLIB$$c4c90fcf.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88) at com.pmacsbackground.nbi.config.LogAspect.logExecutionTime(LogAspect.java:22) at sun.reflect.GeneratedMethodAccessor397.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633) at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
最新发布
06-20
<think>我们正在解决Hutool库中HTTP请求在特定方法`sendAlarmClearToHiNMS`中出现的读取超时问题,并希望使用SpringAOP进行异常处理。问题:在调用`sendAlarmClearToHiNMS`方法时,可能会抛出`cn.hutool.http.HttpException:Readtimedout`,我们需要捕获这个异常并进行处理。解决方案分为两部分:1.调整HutoolHTTP请求的超时设置,避免超时发生(如之前所述)。2.使用SpringAOP对`sendAlarmClearToHiNMS`方法进行异常处理,以便在超时发生时执行特定的逻辑(如重试、记录日志、返回默认值等)。由于用户特别提到要使用SpringAOP进行异常处理,我们将重点放在第二部分。步骤:1.创建一个切面(Aspect)类,用于捕获目标方法抛出的异常。2.定义切点(Pointcut)匹配`sendAlarmClearToHiNMS`方法。3.编写异常通知(AfterThrowingadvice)或环绕通知(Aroundadvice)来处理异常。示例代码:首先,确保SpringBoot项目已经包含AOP依赖(如spring-boot-starter-aop)。然后,创建一个切面类:```javaimportcn.hutool.http.HttpException;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.springframework.stereotype.Component;@Aspect@ComponentpublicclassHttpTimeoutAspect{//定义切点:指向sendAlarmClearToHiNMS方法,这里假设方法在AlarmService类中//请根据实际包路径和方法签名修改@Around("execution(*com.example.service.AlarmService.sendAlarmClearToHiNMS(..))")publicObjecthandleHttpTimeout(ProceedingJoinPointjoinPoint)throwsThrowable{try{//执行原方法returnjoinPoint.proceed();}catch(HttpExceptione){//检查异常原因是否为Readtimedoutif(e.getCause()instanceofjava.net.SocketTimeoutException){//处理超时异常,例如:记录日志、重试、返回默认值等//这里示例为记录日志并重试一次System.out.println("发生HTTP读取超时,尝试重试...");try{returnjoinPoint.proceed();//重试一次}catch(Exceptionex){//重试后仍然失败,记录并返回默认值或抛出其他异常System.out.println("重试失败,返回默认值");returnnull;//或者根据业务返回默认值}}else{throwe;//其他类型的HttpException,继续抛出}}}}```注意:-上述示例中,我们使用环绕通知(@Around)来包裹目标方法,这样可以在捕获异常后进行重试。-重试逻辑:这里简单重试一次,实际应用中可能需要控制重试次数和间隔,避免立即重试仍失败。也可以使用SpringRetry模块来实现更复杂的重试策略。-如果不想重试,也可以记录日志并返回一个默认值,或者抛出一个自定义异常。另一种方式:使用@AfterThrowing通知(仅捕获异常,不能改变流程),但通常我们需要在超时时进行重试,所以环绕通知更合适。优化重试:使用指数退避策略或固定间隔重试,可以引入SpringRetry。如果使用SpringRetry,首先添加依赖:```xml<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId></dependency>```然后在配置类上启用重试:```java@EnableRetry@SpringBootApplicationpublicclassApplication{...}```在方法上使用@Retryable注解(但这里我们需要结合AOP,因为我们要捕获特定异常才重试):我们可以直接在`sendAlarmClearToHiNMS`方法上使用@Retryable,但这样会侵入业务代码。因此,我们可以在切面中整合重试逻辑,或者使用AOP+重试模板。这里提供在切面中实现简单重试(固定次数)的代码:```java@Around("execution(*com.example.service.AlarmService.sendAlarmClearToHiNMS(..))")publicObjecthandleHttpTimeoutWithRetries(ProceedingJoinPointjoinPoint)throwsThrowable{intmaxRetries=3;intattempt=0;ThrowablelastException=null;while(attempt<maxRetries){attempt++;try{returnjoinPoint.proceed();}catch(HttpExceptione){if(e.getCause()instanceofjava.net.SocketTimeoutException){lastException=e;System.out.println("HTTP读取超时,第"+attempt+"次重试...");//可以等待一段时间再重试Thread.sleep(1000*attempt);//等待时间递增:1s,2s,3s...}else{throwe;}}}//重试多次后仍然失败System.out.println("重试"+maxRetries+"次后失败");throwlastException;//或者返回默认值}```总结:1.使用SpringAOP环绕通知捕获目标方法的HttpException异常。2.判断异常原因是否为SocketTimeoutException(读取超时)。3.执行重试逻辑(可设置重试次数和等待时间)。4.重试多次失败后,抛出异常或返回默认值。注意:重试操作可能会增加响应时间,因此需要根据业务需求调整重试次数和等待时间。另外,针对超时问题,我们仍然建议调整Hutool的超时时间设置,以减少超时发生的概率。例如,在`sendAlarmClearToHiNMS`方法中设置更长的读取超时:```javapublicvoidsendAlarmClearToHiNMS(){//使用Hutool发送请求HttpRequest.post("http://example.com/api").setReadTimeout(60000)//60秒.execute();}```通过结合设置合理的超时时间和AOP异常处理(含重试),可以显著提高系统的健壮性。§§相关问题§§1.如何在SpringAOP中捕获特定异常并进行重试?2.如何配置Hutool的HTTP请求超时时间?3.SpringRetry模块的使用方法是什么?4.如何处理HTTP请求中的其他网络异常(如连接超时)?</think>### Hutool HTTP超时异常处理方案(结合Spring AOP) 针对`sendAlarmClearToHiNMS`方法中的Hutool HTTP读取超时问题,以下是完整的异常处理方案,结合Spring AOP实现统一异常处理: #### 1. **核心异常处理逻辑** ```java import cn.hutool.http.HttpException; import java.net.SocketTimeoutException; public class AlarmService { public void sendAlarmClearToHiNMS() { try { // Hutool HTTP请求(显式设置超时) HttpRequest.post("https://api.hinms.com/alarm/clear") .setConnectionTimeout(5000) .setReadTimeout(30000) // 关键:调大读取超时 .body(JsonUtil.toJson(alarmData)) .execute(); } catch (HttpException e) { if (e.getCause() instanceof SocketTimeoutException) { // 专属超时处理逻辑 handleTimeout(e); } else { throw new AlarmServiceException("HTTP请求失败", e); } } } private void handleTimeout(HttpException e) { // 1. 记录详细日志 log.error("NMS接口超时: {}", e.getMessage()); // 2. 重试机制(示例) if(retryCount < MAX_RETRY) { retryCount++; sendAlarmClearToHiNMS(); // 递归重试 } // 3. 触发备用通道 backupService.notifyAlarm(); } } ``` #### 2. **Spring AOP全局异常处理** ```java import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect @Component public class HttpTimeoutAspect { // 拦截指定包下的所有方法 @AfterThrowing( pointcut = "execution(* com.yourpackage..*.*(..))", throwing = "ex" ) public void handleHttpException(HttpException ex) { if (ex.getCause() instanceof SocketTimeoutException) { // 统一超时处理 Metrics.counter("http_timeout_errors").increment(); AlertService.sendCriticalAlert("NMS接口超时告警"); } } } ``` #### 3. **关键配置优化** ```yaml # application.yml hutool: http: global-timeout: 30000 # 全局超时设置 max-redirects: 2 # 重定向次数 ``` #### 4. **深度优化建议** 1. **连接池配置**(防资源泄漏) ```java // 创建自定义连接池 PooledHttpClient client = HttpUtil.createHttpClientBuilder() .setMaxConnTotal(20) .setMaxConnPerRoute(5) .build(); ``` 2. **熔断机制**(Hystrix集成) ```java @HystrixCommand( fallbackMethod = "fallbackHandler", commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="40000") } ) public void sendAlarmClearToHiNMS() { ... } ``` 3. **异步处理**(防线程阻塞) ```java @Async("httpTaskExecutor") public CompletableFuture<Void> asyncSendAlarm() { // HTTP调用逻辑 } ``` #### 5. **监控增强** ```java // 在AOP中添加Prometheus监控 @AfterThrowing(...) public void monitorTimeout(HttpException ex) { // 记录超时URL和持续时间 Timer.builder("http_request_duration") .tag("uri", currentUri) .register(prometheusMeterRegistry) .record(timeoutDuration, TimeUnit.MILLISECONDS); } ``` > **重要原则**: > 1. 超时时间设置应遵循:$$T_{total} = T_{connect} + T_{read} \times (retry+1)$$ > 2. 生产环境推荐值: > - 常规请求:$T_{read} \geq 10s$ > - 文件传输:$T_{read} \geq 60s$ > 3. 结合Spring Boot的错误处理机制[^1],确保未提交响应时的异常转发
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值