嗨,我有一个没有触发的Aspect的问题,我不知道为什么。以下是我的项目:
注释:
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>
知道为什么没有触发方面?
答案 0 :(得分:0)
@Around
中是否缺少Profiled Annotation@Around("@annotation(com.example.Profiled)")
public Object profile(ProceedingJoinPoint pjp, Profiled annotation) throws Throwable {
...
}
答案 1 :(得分:0)
您可以将方面设为@Component
并通过组件扫描获取它,而不是手动实例化。
另一个想法是使用@EnableAspectJAutoProxy(proxyTargetClass=true)
因为你的目标类没有实现可以由JDK代理代理的接口,而是一个简单的类。为此,您需要一个CGLIB代理。