如何在Spring Boot中对私有/受保护的请求映射执行AOP

如何在Spring Boot中对私有/受保护的请求映射执行AOP,spring,spring-boot,aop,aspectj,Spring,Spring Boot,Aop,Aspectj,我想对下面的@RequestMapping方法调用执行AOP,注意hello()方法是非公共的 @RestController class HelloController { @RequestMapping(value = "/hello", method = RequestMethod.GET) String hello() { return "Hello"; } } 这是主类,我添加了@Aspect、@enableSpectJautoproxy注释

我想对下面的@RequestMapping方法调用执行AOP,注意hello()方法是公共的

@RestController
class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    String hello() {
        return "Hello";
    }
}
这是主类,我添加了@Aspect、@enableSpectJautoproxy注释

@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
@SpringBootApplication
public class FooServiceApplication {

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

    @Around("@annotation(requestMapping)")
    public Object around(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {
        return pjp.proceed();
    }
}
在pom.xml中,我只添加了以下依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

org.springframework.boot
SpringBootStarterWeb
org.springframework.boot
弹簧启动机aop
结果是,如果hello()方法是public的,AOP将正常工作,但是如果与上面的示例相同,没有公共声明,AOP将根本不工作。但是,是不是enableSpectProxy将使用CGLIB并可以拦截受保护/私有方法调用?

根据Spring基于代理的AOP只能拦截
公共方法

由于Spring的AOP框架基于代理的特性,受保护的方法根据定义是不被拦截的,既不适用于JDK代理(如果这不适用),也不适用于CGLIB代理(如果这在技术上是可能的,但不推荐用于AOP目的)。因此,任何给定的切入点将只与公共方法匹配

如果您的侦听需要包括受保护的/私有的方法,甚至是构造函数,请考虑使用Spring驱动的原生AspectJ编织,而不是Spring基于代理的AOP框架。这构成了一种不同的AOP使用模式,具有不同的特性,因此在做出决定之前,一定要先熟悉编织

在决定使用AspectJ编织之前,我建议您阅读文档中的,以帮助您做出决定

可供替代的 根据你想要达到的目标,你也可以考虑使用./P> 过滤器拦截每个请求,并具有添加/删除头、验证、日志等功能。;通常执行通用/应用程序范围的操作

要添加一个类,只需声明一个类

import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class SomeFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        /*execute your logic*/
        if (/* request may proceed*/) {
            chain.doFilter(request,response);
        } else {
            /* write response */
        }
    }
}

不,它不能,这是基于代理的AOP的限制。@M.Deinum我已经检查过了,可以使用Spring驱动来解决这个问题,但不推荐,对吗?谢谢回复,我已经注意到了上面提到的Spring文档。由于不太熟悉Spring,是否有任何方法可以在Spring上下文中拦截RestController来进行定制而不使用AOP,而是利用Spring自己的接口或回调?这实际上取决于“进行定制”的含义:)。您可能还需要阅读过滤器,看看它是否适合您的定制需求。(最新答覆)