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



我已经定义了一个方面来包装我的@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已经这样做了。我还需要指定注释吗?或者我可以仅根据参数类型执行此操作吗?哪种方法最有效?

如果您要使用基于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();
}

最新更新