0

我正在尝试在没有 aspectweaver 和 spring-instrument 的 javaagent jar 文件的情况下启用 loadtimeweaving。这是我为实现相同目标而实施的,但它不起作用。

@ComponentScan("com.myapplication")
@EnableAspectJAutoProxy
@EnableSpringConfigured
@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.AUTODETECT)
public class AopConfig implements LoadTimeWeavingConfigurer {
 
 @Override
 public LoadTimeWeaver getLoadTimeWeaver() {
     return new ReflectiveLoadTimeWeaver();
 }
 
  /**
  * Makes the aspect a Spring bean, eligible for receiving autowired components.
  */
 @Bean
 public InstrumentationLoadTimeWeaver loadTimeWeaver()  throws Throwable {
     InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
     return loadTimeWeaver;
 }

}
4

1 回答 1

0

我发现的一种解决方法是热附加InstrumentationSavingAgentspring-instrument而不是通过-javaagent命令行参数启动代理。但为此,您需要一个Instrumentation实例。我只是使用了可以做到这一点的微型助手库byte-buddy-helper(独立于 ByteBuddy 工作,别担心)。确保在 Java 9+ JVM 中,如果由于某种原因无法正常工作,则激活 Attach API。

所以摆脱implements LoadTimeWeavingConfigurer配置类中的两个工厂方法,然后这样做:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-instrument</artifactId>
</dependency>
<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy-agent</artifactId>
    <version>1.10.14</version>
</dependency>
@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    Instrumentation instrumentation = ByteBuddyAgent.install();
    InstrumentationSavingAgent.premain("", instrumentation);
    ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    // ...
  }
}

如果您有任何不明白的地方,请随时提出后续问题。


更新:我注意到的另一件事是,这仅适用于我aspectjWeaving = ENABLED,不适用于AUTODETECT. 对于一个示例 Spring bean,我注意到它@Component不起作用,可能是因为 Spring 与 AspectJ 之间存在一些引导问题。因此,我用显式@Bean配置替换了它,然后它就起作用了。像这样的东西:

@Configuration
@ComponentScan("com.spring.aspect.dynamicflow")
@EnableLoadTimeWeaving(aspectjWeaving = ENABLED)
public class ApplicationConfig {
  @Bean
  public JobProcess jobProcess() {
    return new JobProcessImpl();
  }
}
于 2020-09-14T02:09:46.670 回答