在运行时在方面中注入方法参数值
Inject a method parameter value at runtime in an aspect
我已经定义了一个将包装我的@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?
如何做到这一点?我确定这是可能的,因为 Spring 已经做到了,例如,如果我将 HttpServletRequest 作为参数。我还需要指定注释吗?或者我可以只根据参数类型来做吗?哪种方法最有效?
如果您要寻求基于 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();
}
我已经定义了一个将包装我的@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?
如何做到这一点?我确定这是可能的,因为 Spring 已经做到了,例如,如果我将 HttpServletRequest 作为参数。我还需要指定注释吗?或者我可以只根据参数类型来做吗?哪种方法最有效?
如果您要寻求基于 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();
}