Spring - Intercepting bean creation and injecting custom proxy

后端 未结 4 1614
孤独总比滥情好
孤独总比滥情好 2021-02-13 16:07

I have a @Controller with @Autowired fields and handler methods that I want to annotate with custom annotations.

For example,

         


        
4条回答
  •  被撕碎了的回忆
    2021-02-13 16:48

    Take a look at Spring AOP. It has exactly the facilities you are after. For your example, you could do something like this:

    @Aspect
    @Component
    public class MyAspect {
        @Around("@annotation(path.to.your.annotation.OnlyIfXYZ)")
        public Object onlyIfXyz(final ProceedingJoinPoint pjp) throws Exception {
            //do some stuff before invoking methods annotated with @OnlyIfXYZ
            final Object returnValue = pjp.proceed();
            //do some stuff after invoking methods annotated with @OnlyIfXYZ
            return returnValue;
        }
    }
    

    It is worth noting that Spring will only apply the proxy to classes that are a part of its application context. (which it appears is the case in your example)

    You can also use Spring AOP to bind parameters to your aspect method. This can be done in various ways, but the one you are after is probably args(paramName).

    @Aspect
    @Component
    public class MyAspect2 {
        @Around("@annotation(path.to.your.annotation.OnlyIfXYZ) && " +
            "args(..,request,..)")
        public Object onlyIfXyzAndHasHttpServletRequest(final ProceedingJoinPoint pjp,
                final HttpServletRequest request) throws Exception {
            //do some stuff before invoking methods annotated with @OnlyIfXYZ
            //do something special with your HttpServletRequest
            final Object returnValue = pjp.proceed();
            //do some stuff after invoking methods annotated with @OnlyIfXYZ
            //do more special things with your HttpServletRequest
            return returnValue;
        }
    }
    

    This aspect should do a part of what you are after. It will proxy methods annotated with @OnlyIfXYZ that ALSO take in a HttpServletRequest as a parameter. Further, it will bind this HttpServletRequest into the Aspect method as a passed in parameter.

    I understand that you are after potentially both HttpServletRequest and HttpServletResponse, so you should be able to modify the args expression to take in both request and response.

提交回复
热议问题