为了账号安全,请及时绑定邮箱和手机立即绑定

在不同项目中用作编译的 jar 时,Spring AOP 不起作用

在不同项目中用作编译的 jar 时,Spring AOP 不起作用

绝地无双 2021-09-15 15:55:48
我有一个可用的 AOP(在它被写入的项目内部使用时)但是当我构建这个项目(maven 安装)并在另一个项目中使用该 JAR 并尝试使用@TimedLog注释时,没有任何反应。我试图断点到它,但它没有到达那里。它看起来像这样:@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface TimedLog {    boolean shouldAttachMethodArgs() default false;    boolean shouldAttachReturnValue() default false;    String message() default "";}这是实际的方面:@Aspect@Configuration@Slf4jpublic class MethodExecutionAspect {    @Pointcut("@annotation(timedLogVar)")    public void annotationPointCutDefinition(TimedLog timedLogVar) {}    @Pointcut("execution(* *(..))")    public void atExecution() {}    @Around(value = "annotationPointCutDefinition(timedLogVar) && atExecution()", argNames = "joinPoint,timedLogVar")    public Object around(ProceedingJoinPoint joinPoint, TimedLog timedLogVar) throws Throwable {        Stopwatch stopwatch = Stopwatch.createStarted();        Object returnValue = joinPoint.proceed();        stopwatch.stop();        log.info(String.format("test message %s", stopwatch.elapsed(TimeUnit.MILLISECONDS)));        return returnValue;    }}它的一个实现是:@TimedLogvoid testDefaultValues() throws InterruptedException {    int sleepTimeInMillis = 200;    log.info("Resting for {} millis", value("sleepTimeInMillis", sleepTimeInMillis));    Thread.sleep(sleepTimeInMillis);}pom.xml<!-- AOP --><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-aop</artifactId>    <version>5.0.2.RELEASE</version>    <scope>compile</scope></dependency><dependency>    <groupId>org.aspectj</groupId>    <artifactId>aspectjweaver</artifactId>    <version>1.8.13</version>    <scope>compile</scope></dependency>从这里可以看到,这是一个装饰方法并记录其运行时的 AOP。我已经为此苦苦挣扎了一段时间,非常感谢您的帮助。
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

要使方面起作用,您需要启用它们。要启用您需要通过 xml 或通过注释配置它们:


@Configuration

@EnableAspectJAutoProxy

通过xml:


<beans …>

      <!– Enable AspectJ auto-wiring –>

      <aop:aspectj-autoproxy />

</beans>

当您将 jar 包含到另一个应用程序中时,这个其他应用程序有自己的配置和上下文。即使您为原始上下文启用了方面自动装配,您仍然需要通过上述两种方式之一为新应用程序执行相同的操作。


如果您使用注释,请确保它在组件扫描范围内,并且它确实包含在您的上下文中。


更新:@Import (MethodExecutionAspect.class)对您的 testingSomethingTest 执行以确保它是组件扫描的。


查看完整回答
反对 回复 2021-09-15
  • 1 回答
  • 0 关注
  • 286 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信