Spring XML Aspect before Annotation an Class not working

Viewed 29

i'm currently trying to using a custom annotation at method and class level to execute code via an aspect. It is a SAP Commerce Cloud project (newest version).

On method level it works fine but if the annotation is on the class it doesn't enter my Aspect. Why? Hope someone can help me.

Annotation

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserGroupAuthorize {

    UserGroup[] groups() default {};

}

spring.xml

    <aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true"/>

    <bean id="userGroupAuthorizeAspect" class="com.[...].annotation.UserGroupAuthorizeAspect">
        <constructor-arg name="userService" ref="userService"/>
    </bean>
    <aop:config proxy-target-class="true">
        <aop:aspect id="userGroupAuthorizeAspectId" ref="userGroupAuthorizeAspect">
            <aop:pointcut id="userGroupAuthorizeAnnotation" expression="@annotation(userGroupAuthorize)"/>
            <aop:before pointcut-ref="userGroupAuthorizeAnnotation" method="authorize"/>
        </aop:aspect>
    </aop:config>

Aspect

public class UserGroupAuthorizeAspect {

    public void authorize(UserGroupAuthorize userGroupAuthorize) {
       ...
    }
...
}

Usages

@UserGroupAuthorize(groups = {UserGroup.CUSTOMER, UserGroup.CUSTOMER_MANAGERGROUP})

like said on method(works) or on class(works not)

1 Answers

finally I found a solution on Baeldung: https://www.baeldung.com/aspectj-advise-methods

my solution looks like this:

    <aop:config proxy-target-class="true">
        <aop:aspect ref="userGroupAuthorizeAspect">
            <aop:before pointcut="@annotation(userGroupAuthorize)" 
                        method="authorizeMethod"/>
        </aop:aspect>
        <aop:aspect ref="userGroupAuthorizeAspect">
            <aop:around pointcut="@within(com.[...].annotation.UserGroupAuthorize) and execution(* *(..))" 
                        method="authorizeClass"/>
        </aop:aspect>
    </aop:config>
    public Object authorizeClass(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        UserGroupAuthorize userGroupAuthorize = signature.getMethod().getDeclaringClass()
            .getAnnotation(UserGroupAuthorize.class);
        authorizeMethod(userGroupAuthorize);
        return pjp.proceed();
    }
Related