在某个方面在运行时注入方法参数值

问题描述 投票:0回答:1

我已经定义了一个方面,它将包装我的@RestControllers:

@Aspect
@Order(1)
public class ControllerAspect {

    @Around("controllerinvocation()")
    public Object doThings(ProceeedingJoinpoint pj) throws Throwable{
          //before I would set MyObject values
         return pj.proceed();
    }
}

我想这样做,如果我的控制器将MyObject的实例公开为参数,则用值填充它:

public void controllerMethod(MyObject obj, /* any other parameter */) { //of course obj is null now, how can I fill it?

如何执行此操作?我肯定知道,如果我将HttpServletRequest作为参数,那么Spring已经可以做到了。我是否还需要指定一个注释?还是只能基于参数类型来做到这一点?哪种方法最有效?

spring-boot aspectj
1个回答
0
投票

如果要使用基于aop的解决方案,那么类似的事情就可以完成任务

@Around( value = "execution( // your execution )" )
public Object doThings( ProceedingJoinPoint joinPoint ) throws Throwable
{
    Object[] args = joinPoint.getArgs();

    for( Object arg : args )
    {
        if( arg instanceof MyObject )
        {
            MyObject sampleMyObj = new MyObject (); // Create the dummy value
            return joinPoint.proceed( new Object[] { sampleMyObj, // other args if any } ); // Pass this to the method
        }
    }

    return joinPoint.proceed();
}
© www.soinside.com 2019 - 2024. All rights reserved.