试图截获jdbc操作并用byte buddy返回固定值

omtl5h9j  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(275)

我尝试使用byte buddy和spring来拦截对jdbccoperations的调用。
我有两节课。
应用程序.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);
         }

    }
}

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

bxjv4tth

bxjv4tth1#

ElementMatchers.is(JdbcOperations.class) ,您正在加载 JdbcOperations 班级。如果不重新传输,则不会检测此类,因为在安装代理时已经加载了此类。
宁可使用 ElementMatchers.named("pkg.of.JdbcOperations") .

相关问题