One of the differences would be, as your example shows, with a decorator you usually write 1 decorator per 1 decorated class / interface.
With interceptors that are part of the AOP concept, you write 1 interceptor for a bunch of classes / methods, for example. you intercept all DAOs and make sure that the transaction is open before the call and closed after it.
An example of an interceptor in spring AOP, firstly, you declare a pointcut (what you need), here you match any method from the MyDao class that starts with the insert , contains any arguments and any return type.
@Pointcut("execution(* com.example.dao.MyDao.insert*(..))") public void insertPointcut() { }
Then you post around a board that references pointcut
@Around(value = "com.example.SystemArchitecture.insertPointcut()") public void interceptMethod(ProceedingJoinPoint pjp) { // do pre-work Object retVal = pjp.proceed(); // do post work return retVal; } }
However, each part has its own pro / cons. For example. interceptors are more flexible, but imagine that you change the name of the method, if you use a decorator, you will probably get a compiler error, with interceptors, it just won't match and won't execute your logic around.
Bax
source share