سؤال

How do we configure annotation based spring aspect in java?

Lets say we want to intercept a spring service, we usually do it by AOP pointcut expression. This example details how to do it using annotation instead of expression. This is more portable as we use annotation.

There are many examples but very few have the right content. Hence putting it here...

This is a solved question. I am posting my answer so it helps others including myself..

هل كانت مفيدة؟

المحلول

Annotation based AOP advice in spring

1.define annotation

 public @interface ApplyAuthorisationAdvice {
 }

Set <aop:aspectj-autoproxy /> in spring config file if not done before

2.

import org.aopalliance.aop.Advice;
import org.aspectj.lang.annotation.Aspect;

@Aspect
@Component
public class AuthorisationAspect implements Advice {

    private final static Logger logger = Logger.getLogger(AuthorisationAspect.class);

    @Autowired
    MyService myService;

    @SuppressWarnings("unchecked")
    @AfterReturning(pointcut = "@annotation(com.example.ApplyAuthorisationAdvice)", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {

        if (result != null && (result instanceof List)) {
            // filter stuff
        }

    }
}

3.Apply annotation on service which needs to be intercepted

@Component("myService")
public class MyServiceImpl implements MyService {
  @ApplyAuthorisationAdvice 
   public List<MySummary> search(MyContext searchContext) {
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top