/ / Spring AOP i Post Construct - spring, spring-mvc, aop, aspektj, postconstruct

Spring AOP i Post Construct - wiosna, wiosna-mvc, aop, aspektj, postkonstrukcja

Chcę napisać nazwę metody używającej @PostConstruct. Odkryłem jednak, że AOP nie jest w stanie „dookoła” metody PostConstruct. Czy jest jakiś sposób na użycie AOP z metodą PostConstruct?

Odpowiedzi:

4 dla odpowiedzi № 1

Spróbuj tego.

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

Dodatkowo musisz aktywować tkanie w czasie kompilacji. Opublikowałem projekt demonstracyjny na github, który wykorzystuje maven. Klon https://github.com/jannikweichert/PostConstructAOPDemo i wykonaj

mvn clean compile spring-boot:run

Następnie powinieneś zobaczyć w Sysout:

This is before test()
test() is executed

Cieszyć się!


3 dla odpowiedzi № 2

Adnotacje @PostConstruct i @PreDestroysą częścią biblioteki J2ee, a nie częścią Spring AOP. Dlatego domyślnie Spring nie będzie wiedział o adnotacjach @PostConstruct i @PreDestroy. Aby go włączyć, musisz zarejestrować „CommonAnnotationBeanPostProcessor” lub określić tak jak „W pliku konfiguracyjnym fasoli,

<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>

Lub jak

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

i opatrz komentarz swoją metodą

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

1 dla odpowiedzi nr 3

Spring AOP jest oparty na proxy. O ile nie skonfigurowano inaczej, Spring AOP performs run-time weaving i @PostConstruct wykonuje się w czasie ładowania aplikacji.

Umożliwić @PostConstruct do wykonania przez @Around porady w czasie ładowania musisz skonfigurować Wiosna tkanie w czasie ładowania. Po skonfigurowaniu użyj @annotation jako wiążący formularz dla @Around porady w następujący sposób:

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