【问题标题】:Trying to intercept jdbcOperations and return fixed value with byte buddy试图拦截 jdbcOperations 并使用字节伙伴返回固定值
【发布时间】:2021-02-26 13:56:51
【问题描述】:

我正在尝试使用 byte buddy 和 spring 来拦截对 JdbcOperations 的调用。

我有两节课。

Application.java

    @SpringBootApplication
    public class Application {

    public static void main(String[] args) throws Exception{
        premain(null, ByteBuddyAgent.install());
        SpringApplication.run(Application.class, args);
    }


    public static void premain(String arg, Instrumentation instrumentation) throws Exception {
        new AgentBuilder.Default()
                .type(ElementMatchers.is(JdbcOperations.class))
                .transform(new AgentBuilder.Transformer() {
                    @Override
                    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
                        return builder.method(named("queryForList"))
                                .intercept(FixedValue.value(Collections.emptyList()));
                    }
                }).installOn(instrumentation);
    }
} 

DemoRunner.java

    @Component
    public class DemoRunner implements CommandLineRunner {
    private final JdbcOperations jdbcOperations;

    public DemoRunner(JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }


    @Override
    public void run(String... args) throws Exception {
         List<Map<String,Object>> resultSet = jdbcOperations.queryForList("SELECT * FROM COUNTRY");

         for(Map<String, Object> result : resultSet) {
             System.out.println(result);
         }

    }
}

我可以看到代码运行,但它没有像我预期的那样返回固定值。有人知道我哪里出错了吗?

【问题讨论】:

    标签: java spring instrumentation byte-buddy


    【解决方案1】:

    使用ElementMatchers.is(JdbcOperations.class),您正在加载JdbcOperations 类。如果不重新转换,此类将不会被检测,因为它在安装代理时已经加载。

    宁可使用ElementMatchers.named("pkg.of.JdbcOperations")

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多