gpt4 book ai didi

java - Spring Boot AOP 不适用于 AfterThrow

转载 作者:行者123 更新时间:2023-11-30 03:15:51 26 4
gpt4 key购买 nike

package test.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
@Aspect
class LoggingMonitor {

@AfterThrowing(
pointcut = "execution(* test.aop..foo(..))",
throwing = "error")
public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
System.out.println(joinPoint);
}
}

@Service
class MyBean {
void foo() {
throw new RuntimeException("run error");
}
}

@SpringBootApplication
public class App {
@Autowired
MyBean myBean;

@Bean
CommandLineRunner runner() {
return r -> {
System.out.println("Run");
myBean.foo();
};
}

public static void main(String[] args) {
SpringApplication.run(App.class);
}
}

我不明白为什么上面的代码不起作用,但是当我将切入点更改为“* org.springframework.boot.CommandLineRunner.run(..)”时,它起作用了。

最佳答案

Spring AOP 仅适用于公共(public)方法。公开您的方法,或恢复到 AspectJ。

Due to the proxy-based nature of Spring’s AOP framework, protected methods are by definition not intercepted, neither for JDK proxies (where this isn’t applicable) nor for CGLIB proxies (where this is technically possible but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only! If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.

Source

关于java - Spring Boot AOP 不适用于 AfterThrow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com