我尝试使用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);
}
}
}
我可以看到代码运行了,但是它没有像我期望的那样返回固定值。有人知道我哪里出错了吗?
1条答案
按热度按时间bxjv4tth1#
与
ElementMatchers.is(JdbcOperations.class)
,您正在加载JdbcOperations
班级。如果不重新传输,则不会检测此类,因为在安装代理时已经加载了此类。宁可使用
ElementMatchers.named("pkg.of.JdbcOperations")
.