[英]AOP spring aspect not triggered
嗨,我遇到了一個未觸發的方面問題,我也不知道為什么。 這是我的項目:
注釋:
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Profiled {
}
方面:
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class ProfiledAspect {
final static Logger logger = Logger.getLogger(ProfiledAspect.class);
private final String TIME_UNIT = "ms";
@Around("@annotation(annotation)")
public Object profile(ProceedingJoinPoint pjp, Profiled annotation) throws Throwable {
long start = System.nanoTime();
Object result = pjp.proceed();
long end= System.nanoTime();
long duration = end - start;
System.out.println("Duration: " + duration + "nano secs.");
return result;
}
}
這是我的配置類:
import com.myexample.aop.ProfiledAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = {"com.myexample"})
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public ProfiledAspect profiledAspect(){
return new ProfiledAspect();
}
}
這是我在課堂上使用注解觸發方面的地方:
import com.myexample.aop.Profiled;
import org.springframework.stereotype.Service;
@Service
public class TestAnnotationClass {
@Profiled
public void testAnnotationClass() {
System.out.println("test profile annotation");
}
}
這是我用於AOP的Maven依賴項
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
知道為什么不觸發方面嗎?
@Around中是否缺少分析注釋
@Around("@annotation(com.example.Profiled)")
public Object profile(ProceedingJoinPoint pjp, Profiled annotation) throws Throwable {
...
}
您可以將方面也@Component
並通過組件掃描將其拾取,而不是手動實例化它。
另一個想法是使用@EnableAspectJAutoProxy(proxyTargetClass=true)
因為您的目標類沒有實現一個可以由JDK代理代理的接口,而是一個簡單的類。 為此,您需要一個CGLIB代理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.