问题描述
我尝试使用bytebuddy在springboot中实现aop。代码如下:
package klordy.learning.annotation;
@Target(METHOD)
@Retention(RUNTIME)
@Documented
public @interface CostTime {
}
package klordy.learning.agent;
public class Agent {
private static Agent instance = new Agent();
private Logger logger = LoggerFactory.getLogger(Agent.class);
private Agent() {}
public static Agent getInstance(){ return instance; }
public void install() {
ByteBuddyAgent.install();
AgentBuilder.Listener listener = new AgentBuilder.Listener() {
// do nothing
...
};
new AgentBuilder.Default()
.type(ElementMatchers.nameStartsWith("klordy.learning"))
.transform((builder,typeDescription,classLoader,module) ->
builder.visit(Advice.to(TimeAdvice.class).on(ElementMatchers.isAnnotatedWith(named("klordy.learning.annotation.CostTime")))))
.with(listener)
// *** added as supposed,but still seems not work.
.with(AgentBuilder.RedeFinitionStrategy.RETRANSFORMATION)
.installOnByteBuddyAgent();
logger.info("byte buddy modification done.");
}
}
public class TimeAdvice {
@Advice.OnMethodEnter
static long enter(@Advice.AllArguments Object args[],@Advice.Origin Method method){
return System.currentTimeMillis();
}
@Advice.OnMethodExit
static void exit(@Advice.Enter long startTime,@Advice.Return(typing = Assigner.Typing.DYNAMIC) Object result,@Advice.Origin Method method,@Advice.Thrown Throwable throwable){
if(throwable != null){
System.out.println("error func " + System.currentTimeMillis());
}else {
System.out.println("func takes " + (System.currentTimeMillis() - startTime));
}
}
}
springboot的侦听器,如下所示:
public class AppEnvListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
private Logger logger = LoggerFactory.getLogger(AppEnvListener.class);
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
Agent.getInstance().install();
logger.info("finished byte buddy installation.");
}
}
最后,在springboot启动中注册侦听器:
@SpringBootApplication
@ComponentScan(basePackages = "klordy.learning")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SpringBootDemoApplication.class);
// register listener
application.addListeners(new AppEnvListener());
application.run(args);
}
}
启动应用程序时,调试记录器显示正常。但是,处理请求时,aop无法正常工作。我究竟做错了什么?我很困惑...
解决方法
您正在讨论的课程可能已经加载。
在您的代理配置中设置.with(RetransformationStrategy.RETRANSFORM)
或安装代理,然后再以main
方法加载Spring。
好的,我想我是通过使用Spring Boot重新创建您的情况来找到您的问题的。但是,即使没有Spring,它也会发生。基本上,您打了this problem。
因此,如果您将建议修改为@Advice.OnMethodExit(onThrowable = Throwable.class)
,就可以了。您还应该将.disableClassFormatChanges()
添加到您的代理BTW。它有助于避免重新转换以前加载的类的问题。 JVM要求不要在结构上进行更改。
我怎么知道发生了什么事?我在ByteBuddy中激活了控制台日志记录。以前,我使用过您的侦听器,使它记录每个动作,因此我可以看到BB实际上正在被触发。但是BB日志记录确实显示了异常,这是由于您错误地使用了@Advice.Thrown
(在建议注释中没有onThrowable = Throwable.class
造成的)。
public void install() {
ByteBuddyAgent.install();
new AgentBuilder.Default()
.disableClassFormatChanges()
.with(RETRANSFORMATION)
.with(AgentBuilder.RedefinitionStrategy.Listener.StreamWriting.toSystemError())
.with(AgentBuilder.Listener.StreamWriting.toSystemError().withTransformationsOnly())
.with(AgentBuilder.InstallationListener.StreamWriting.toSystemError())
.type(ElementMatchers.nameStartsWith("klordy.learning"))
.transform((builder,typeDescription,classLoader,module) ->
builder.visit(
Advice
.to(TimeAdvice.class)
.on(isAnnotatedWith(named("klordy.learning.annotation.CostTime")))
)
)
.installOnByteBuddyAgent();
logger.info("byte buddy modification done.");
}