Spring AOP and Post Construct

2019-07-14 21:39发布

问题:

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?

回答1:

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!



回答2:

The @PostConstruct and @PreDestroy annotations are part of J2ee library and not part of Spring AOP. So By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the as ‘ in bean configuration file,

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

<bean id="mybean" class="mypackage.MyBean">
    <property name="myPropertyName" value="my value" />
</bean>

Or as

<bean id="myBean" class="mypackage.myBEan">
    <property name="myProperty" value="test message value" />
</bean>

and annotate your method

@PostConstruct
public void myMethod() throws Exception {
  System.out.println("PostConstruct : " + myProperty);
} 


回答3:

Spring AOP is proxy based. Unless configured to do otherwise, Spring AOP performs run-time weaving and @PostConstruct executes at load time of an application.

To enable @PostConstruct to be executed by @Around advice at load time you have to set up Spring load-time weaving. Once setup use @annotation as a binding form for @Around advice, as follows:

@Around("@annotation(javax.annotation.PostConstruct)")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("method name: " + joinPoint.getSignature().getName());
}