Aspect does not work with Spring boot application with external jar

Avi picture Avi · Aug 14, 2016 · Viewed 15.3k times · Source

I am trying to create a timer aspect for measuring methods run time.

I created an annotation named @Timer:

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

And then I created the aspect as follows:

@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;
    }

I have a configuration class as follows:

@Configuration
@EnableAspectJAutoProxy
public class MetricsConfiguration {

    @Bean
    public MetricAspect notifyAspect() {
        return new MetricAspect();
    }
}

Everything up until here is defined in a packaged jar which I use as a dependency in my spring boot application

In my spring boot application I import the MetricsConfiguration and I debugged the code and saw that the MetricAspect bean is created.

I use it in code as follows:

@Service
public class MyService {
    ...

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

    ...
}

But my code doesn't reach to the measure method. Not sure what I'm missing.

For completing the picture, I have these dependencies in my pom file added:

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

That's the @Configuration class that imports MetricsConfiguration:

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

}

It's loaded with Spring's automagically configuration loading.

Answer

ka yu Lai picture ka yu Lai · Aug 14, 2016

can @Component or @Configurable solve your issue?

@Aspect
@Component
public class yourAspect {
 ...
}

Enable Spring AOP or AspectJ

EDIT:

I created a project to simulate your issue, seems no problem after all. Is it affected by other issue?

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