假设我有一个用@Bean春季注释的java方法。
范例:
public void coco() {
String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {coco();
String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
};
}
这是控制台输出:
方法:“可可”
方法:“ lambda $ 0”
如您所见,我们可以为非bean方法获取方法名称。但是对于bean方法,我们不是获取方法名称,而是获取由spring管理的通用值(我们得到的是“ lambda $ 0”而不是“ commandLineRunner”。
有没有人知道Spring bean方法名称的解决方案?
提前致谢
将获得方法名称的语句移到lambda表达式之外:
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
return args -> {coco();
System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
};
}
之所以不能从lambda表达式内部完成,是因为该commandLineRunner
方法在代码运行时已经很久了,因为编译器将lambda块转换为隐藏的(合成)方法,并用对的引用替换了lambdas表达式。该方法。
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return MyClass::lambda$0;
}
private synthetic void lambda$0(String... args) {
coco();
String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句