Aspect-oriented programming

Aspect-oriented programming

Aspect

Regular classes or regular classes annotated with the @Aspect annotation.

<br /><br />...



Join point

Always represents a method execution.

Advice

An interceptor, maintaining a chain of interceptors around the join point.

  • Before advice
  • After returning advice
  • After throwing advice
  • After (finally) advice
  • Around advice
<br /><br /><br /><br />

Pointcut

A predicate that matches join points.

<br /><br /><br />

Supported Designators

Common pointcut definitions:

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?)
  • modifiers-pattern: *, public, private, etc. (Spring AOP only supports advising public methods.)
  • ret-type-pattern: int, long, etc.
  • declaring-type-pattern If the class and advice are in the same package then package name is not required.
  • name-pattern: wildcard supported.
  • param-pattern: Two dots(..) means any number and type of parameters.

Any public method:

execution(public * *(..))

Any method with a name beginning with “set”:

execution(* set*(..))

Any method defined by the AccountService interface:

execution(* com.xyz.service.AccountService.*(..))

Any method defined in the service package:

execution(* com.xyz.service.service.*.*(..))

Any method defined in the service package or a sub-package:

execution(* com.xyz.service..*.*(..))

see more @ Sharing common pointcut definitions

Proxies

  • Standard JDK dynamic proxies (by interface) (default)
  • CGLIB proxies (by subclassing)
<!-- force to use CGLIB proxies -->

<!-- other beans defined here... -->

AspectJ

A style of declaring aspects as regular Java classes annotated with annotations.
In Spring AOP, it is not possible to have aspects themselves be the target of advice from other aspects. The @Aspect annotation on a class marks it as an aspect, and hence excludes it from auto-proxying.

@Aspect
public class NotVeryUsefulAspect {
@Pointcut("execution(* transfer(..))") // the pointcut expression
private void anyOldTransfer() {}
}

Enabling @AspectJ Support:

<br />

Example

spring-aop.xml

<br /><br /><br /><br /><br />

EntityAspect

public class EntityAspect {
public void prePersist(final GenericEntity entity) {
entity.setCreatedTime(LocalDateTime.now());
entity.setModifiedTime(entity.getCreatedTime());
}
public void preUpdate(final GenericEntity entity) {
entity.setModifiedTime(LocalDateTime.now());
}
}

Leave a comment