Voglio scrivere il nome del metodo che sta usando con @PostConstruct. Ma ho scoperto che AOP non è in grado di "aggirare" il metodo PostConstruct. Esiste un modo per utilizzare AOP con il metodo PostConstruct?
risposte:
4 per risposta № 1Fai un tentativo.
@Around("@annotation(javax.annotation.PostConstruct)")
public void myAdvice(ProceedingJoinPoint jp) throws Throwable{
System.out.println("This is before " + jp.getSignature().getName() + "()");
jp.proceed();
}
Inoltre, è necessario attivare la tessitura in fase di compilazione. Ho pubblicato un progetto Demo su Github che utilizza Maven. Clone https://github.com/jannikweichert/PostConstructAOPDemo ed esegui
mvn clean compile spring-boot:run
Dopodiché dovresti vedere nel Sysout:
This is before test()
test() is executed
Godere!
3 per risposta № 2
Le annotazioni @PostConstruct e @PreDestroyfanno parte della libreria J2ee e non fanno parte di Spring AOP. Quindi, per impostazione predefinita, Spring non è a conoscenza delle annotazioni @PostConstruct e @PreDestroy. Per abilitarlo, devi registrare "CommonAnnotationBeanPostProcessor" o specificare il come "Nel file di configurazione del bean,
<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>
O come
<bean id="myBean" class="mypackage.myBEan">
<property name="myProperty" value="test message value" />
</bean>
e annota il tuo metodo
@PostConstruct
public void myMethod() throws Exception {
System.out.println("PostConstruct : " + myProperty);
}
1 per risposta № 3
Spring AOP è basato su proxy. Se non configurato per fare diversamente, Spring AOP performs run-time weaving
e @PostConstruct
viene eseguito al momento del caricamento di un'applicazione.
Abilitare @PostConstruct
essere eseguito da @Around
consiglio al momento del caricamento è necessario impostare la primavera tessitura a tempo di caricamento. Dopo l'installazione, utilizzare @annotation
come modulo vincolante per @Around
consulenza, come segue:
@Around("@annotation(javax.annotation.PostConstruct)")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("method name: " + joinPoint.getSignature().getName());
}