Spring AOP和后期构造

Thi*_*inh 3 aop spring aspectj spring-mvc postconstruct

我想写与@PostConstruct一起使用的方法的名称。但是我发现AOP无法“绕过” PostConstruct方法。有什么方法可以将AOP与PostConstruct方法一起使用吗?

Jan*_*ert 5

试试看。

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

另外,您需要激活编译时编织。我在github上发布了一个使用maven的演示项目。克隆https://github.com/jannikweichert/PostConstructAOPDemo并执行

mvn clean compile spring-boot:run
Run Code Online (Sandbox Code Playgroud)

之后,您应该在Sysout中看到:

This is before test()
test() is executed
Run Code Online (Sandbox Code Playgroud)

请享用!