简体   繁体   中英

intercept spring mvc controller call based on annotations

I have the following controller in spring MVC

@GetMapping("/id/kw")
public ModelAndView industryWater(HttpServletRequest request) {
    return someMAV
}

I want to cut into the execution of the controller based on customized annotation

@GetMapping("/id/kw")
@WaterBefore
@WaterAfter
public ModelAndView industryWater(HttpServletRequest request) {
    return someMAV
}

I can probably inject some thing using BEAN postProcessor, but I don't know how to hook my injected part with the controller execution. Also I need to access the context request mav when implementing my water aspect .

I researched a bit BeanPostProcessor , Interceptor , but didn't manage to connect all pieces.

I think you need to use AOP in Spring. that is very useful. it`s using transaction management and using logging etc.

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. If you want a more simple definition you can think of them as a Interceptor but with more options configurations possible. In Spring there are two different constructs that get called “interceptors”. First, there are Handler Interceptors, which are part of the Spring MVC framework and give you the ability to add interceptor logic to requests. But you also have Method Interceptors, which are part of the Spring AOP framework. These are much more general mechanism than Handler Interceptors, but also potentially more complex. In AOP terminology, such interceptors provide a means of coding the “aspects” you're talking about.

Like this :

@Pointcut(" execution (* com.your.controller.industryWater(..))")
public void pointcutDemo() {}

@Before("pointcutDemo())")
public void logBefore(){ } 

@After("pointcutDemo())")
public void logAfter(){ } 

link : https://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/

https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations

http://www.baeldung.com/spring-mvc-handlerinterceptor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM