Load time weaving for non-spring beans in a spring application

帅比萌擦擦* 提交于 2019-12-11 03:34:49

问题


I have a spring boot application with some REST controllers, service classes and helper classes. The controllers and service classes are spring managed while helper classes are not spring managed and mostly contain static methods.

The AspectJ configuration is present in java configuration as follows

@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
public class AspectConfig {

    @Bean
    public LoggingAspect loggingAspect() {
        return new LoggingAspect();
    }
}

The corresponding LoggingAspect class is as follows,

@Aspect
public class LoggingAspect {

    @Before("allMethodsPointcut()")
    public void logBeforeMethod(JoinPoint joinPoint) {
        System.out.println("Entering Method - " + joinPoint.getSignature().getDeclaringType() + "::" + joinPoint.getSignature().getName());
    }

    @After("allMethodsPointcut()")
    public void logAfterMethod(JoinPoint joinPoint) {
        System.out.println("Exiting Method - " + joinPoint.getSignature().getDeclaringType() + "::" + joinPoint.getSignature().getName());
    }

    @Pointcut("execution(* com.test.controller..*(..)) || execution(* com.test.service..*(..)) || execution(* com.test.helper..*(..))")
    public void allMethodsPointcut() {
    }
}
  • When the controller is called, the Aspect enabled logging works for the controller and service functions but not for the helper functions.
  • If we autowire the helper class in the controller, the non-static helper methods start showing the aspectj logs. However, the static helper methods still do not show the aspectj logs

Questions, 1. How can we configure the aspectj advice for classes which are not spring managed i.e. without @Bean, @Autowired, @Component etc. 2. How can we configure aspectj advice for static methods (I am using @EnableLoadTimeWeaving but maybe i am missing something) 3. AspectJ configuration should be java based if possible

Kindly let me know if more details are required


回答1:


Use -javaagent:/path/to/aspectjweaver-<version>.jar as a startup argument to your JVM to enable load-time weaving. Remove @EnableAspectJAutoProxy from your spring configuration so that spring doesn't try to use it's own Spring AOP framework instead of pure AspectJ. Optionally, create META-INF/aop.xml. Add @EnableSpringConfigured if you want to apply spring configuration to beans not managed by spring (@Configurable POJOs).



来源:https://stackoverflow.com/questions/41383941/load-time-weaving-for-non-spring-beans-in-a-spring-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!