programing

스프링 AOP 방법 값 변경 인수 주변 조언

css3 2023. 6. 24. 09:27

스프링 AOP 방법 값 변경 인수 주변 조언

Spring AOP를 사용하여 실행하기 전에 일부 검사를 기반으로 메서드 인수 값을 변경할 수 있습니까?

나의 방법

public String doSomething(final String someText, final boolean doTask) {
    // Some Content
    return "Some Text";
}

조언 방법

public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
    String methodName = methodInvocation.getMethod().getName();

    Object[] arguments = methodInvocation.getArguments();
    if (arguments.length >= 2) {
        if (arguments[0] instanceof String) {
            String content = (String) arguments[0];
            if(content.equalsIgnoreCase("A")) {
                // Set my second argument as false
            } else {
                // Set my second argument as true
            }
        }
    }
    return methodInvocation.proceed();
}

인수에 대한 setter 옵션이 없으므로 메서드 인수 값을 설정하는 방법을 제안해 주십시오.

네, 가능합니다.다음 대신 및 가 필요합니다.

methodInvocation.proceed();

그런 다음 새 인수로 진행을 호출할 수 있습니다. 예:

methodInvocation.proceed(new Object[] {content, false});

http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html#aop-ataspectj-advice-proceeding-with-the-call 을 참조하십시오.

다음을 사용하여 답변을 받았습니다.MethodInvocation

public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
    String methodName = methodInvocation.getMethod().getName();

    Object[] arguments = methodInvocation.getArguments();
    if (arguments.length >= 2) {
        if (arguments[0] instanceof String) {
            String content = (String) arguments[0];
            if(content.equalsIgnoreCase("A")) {
                if (methodInvocation instanceof ReflectiveMethodInvocation) {
                    ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
                    arguments[1] = false;
                    invocation.setArguments(arguments);
                }
            } else {
                if (methodInvocation instanceof ReflectiveMethodInvocation) {
                    ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
                    arguments[1] = true;
                    invocation.setArguments(arguments);
                }
            }
        }
    }
    return methodInvocation.proceed();
}

Spring AOP를 사용하여 다음을 사용하여 포인트 컷을 작성할 수 있습니다.@Around그런 다음 아래 코드를 사용하여 조건에 따라 메서드의 인수를 변경할 수 있습니다.

int index = 0;
Object[] modifiedArgs = proceedingJoinPoint.getArgs();

for (Object arg : proceedingJoinPoint.getArgs()) {
    if (arg instanceof User) {    // Check on what basis argument have to be modified.
        modifiedArgs[index]=user;
       }
    index++;
}
return proceedingJoinPoint.proceed(modifiedArgs);  //Continue with the method with modified arguments.

언급URL : https://stackoverflow.com/questions/32369685/spring-aop-change-value-of-methods-argument-on-around-advice