Home Aspects
Post
Cancel

Aspects

Aspect-oriented programming (AOP) is a programming paradigm that separates (or decouples) out cross-cutting concerns in our objects. It’s common to see logging messages scattered in various places.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Foo {
    private static final Logger LOG = LoggerFactory.getLogger(Foo.class);
 
    public void foo() {
        ...
        LOG.info("Some logging message");
        bar();
        ...
    }

    public void bar() {
        ...
    }
}

Create an Aspect with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Aspect
public class MyAspect {
    private static final Logger LOG = LoggerFactory.getLogger(MyAspect.class);

    @Pointcut("execution(public * Foo.foo(..))")
    public void fooPointCut() {}

    @Before("fooPointCut()")
    public void beforeFoo(JoinPoint joinPoint) {
        ...
    }

    @After("fooPointCut()")
    public void afterFoo(JoinPoint joinPoint) {
        ...
    }
}

The Before advice runs before the execution of the joint point method; and the After advice runs after the execution of the joint point method.

Note that we could also have used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Aspect
public class MyAspect {
    private static final Logger LOG = LoggerFactory.getLogger(MyAspect.class);

    @Before("execution(public * Foo.foo(..))")
    public void beforeFoo(JoinPoint joinPoint) {
        ...
    }

    @After("execution(public * Foo.foo(..))")
    public void afterFoo(JoinPoint joinPoint) {
        ...
    }
}

The above is wordier than the former. When we have to reuse the pointcut, it’s often easier and cleaner to use the former scheme.

See this Spring Documentation for other advices that are available.

This post is licensed under CC BY 4.0 by the author.
Trending Tags