Aspect不适用于带有外部jar的Spring启动应用程序

Avi*_*Avi 15 java aop spring aspectj

我正在尝试为测量方法运行时创建一个计时器方面.

我创建了一个名为的注释@Timer:

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface Timer {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了如下方面:

@Aspect
public class MetricAspect {

    @Autowired
    private MetricsFactory metricsFactory;

    @Pointcut("@annotation(my.package.Timer)")
    public void timerPointcut() {}

    @Around("timerPointcut() ")
    public Object measure(ProceedingJoinPoint joinPoint) throws Throwable {
       /* Aspect logic here */
    }

    private Timer getClassAnnotation(MethodSignature methodSignature) {
        Timer annotation;
        Class<?> clazz = methodSignature.getDeclaringType();
        annotation = clazz.getAnnotation(Timer.class);
        return annotation;
    }
Run Code Online (Sandbox Code Playgroud)

我有一个配置类如下:

@Configuration
@EnableAspectJAutoProxy
public class MetricsConfiguration {

    @Bean
    public MetricAspect notifyAspect() {
        return new MetricAspect();
    }
}
Run Code Online (Sandbox Code Playgroud)

直到这里的所有内容都在一个打包的jar中定义,我在春季启动应用程序中将其用作依赖项

在我的spring启动应用程序中,我导入了MetricsConfiguration并调试了代码并看到了MetricAspectbean的创建.

我在代码中使用它如下:

@Service
public class MyService {
    ...

    @Timer("mymetric")
    public void foo() {
       // Some code here...
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

但我的代码没有达到该measure方法.不知道我错过了什么.

为了完成图片,我在我的pom文件中添加了以下依赖项:

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.7.4</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.7.4</version>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

@Configuration是导入的类MetricsConfiguration:

@Configuration
@EnableAspectJAutoProxy
@Import(MetricsConfiguration.class)
@PropertySource("classpath:application.properties")
public class ApplicationConfiguration {

}
Run Code Online (Sandbox Code Playgroud)

它装载了Spring的自动配置加载.

小智 12

@Component@Configurable解决您的问题?

@Aspect
@Component
public class yourAspect {
 ...
}
Run Code Online (Sandbox Code Playgroud)

启用S​​pring AOP或AspectJ

编辑:

我创建了一个模拟你的问题的项目,毕竟没问题.是否受其他问题的影响?

https://github.com/zerg000000/spring-aspectj-test


vsm*_*kov 5

我无法使用aspectJ 1.8.8spring 4.2.5重现您的问题。是我的 Maven 多模块方法,其方面位于单独的 jar 中。

我稍微修改了您的代码,但没有更改任何注释。唯一可能不同的是我添加了org.springframework:spring-aop依赖项并定义了我的入口点,如下所示:

@Import(MetricsConfiguration.class)
@SpringBootApplication
public class Application {
    // @Bean definitions here //

    public static void main(String[] args) throws InterruptedException {
        ApplicationContext ctx = 
            SpringApplication.run(Application.class, args);
        ctx.getBean(MyService.class).doWork();
    }
}
Run Code Online (Sandbox Code Playgroud)