Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP and Post Construct

I want to write the name of method which is using with @PostConstruct. But I found that AOP is unable to "Around" the PostConstruct method. Is there any way to use AOP with PostConstruct method?

like image 926
Thien Dinh Avatar asked Jan 06 '23 21:01

Thien Dinh


1 Answers

Give this a try.

    @Around("@annotation(javax.annotation.PostConstruct)")
    public void myAdvice(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("This is before " + jp.getSignature().getName() + "()");
        jp.proceed();
    }

Additionally you need to activate compile-time weaving. I published a Demo project on github which uses maven. Clone https://github.com/jannikweichert/PostConstructAOPDemo and execute

mvn clean compile spring-boot:run

After that you should see in the Sysout:

This is before test()
test() is executed

Enjoy!

like image 72
Jannik Weichert Avatar answered Mar 05 '23 14:03

Jannik Weichert