【问题标题】:How to use load time weaving without -javaagent?如何在没有-javaagent的情况下使用加载时间编织?
【发布时间】:2020-09-09 06:56:24
【问题描述】:

我正在尝试在没有 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;
 }

}

【问题讨论】:

    标签: spring spring-boot aspectj load-time-weaving compile-time-weaving


    【解决方案1】:

    我发现的一种解决方法是从spring-instrument 热附加InstrumentationSavingAgent,而不是通过-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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多