spring bean 方法:如何获取方法名称?

spring bean method : how to get method name?

假设我有一个 java 方法 spring 用 @Bean 注释。

示例:

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 +"\"") ;
                    };
}

这是控制台输出:

Méthode : "coco"

Méthode : "lambda[=13=]"

如你所见,我们可以获取非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 块转换为隐藏(合成)方法, 并用对该方法的引用替换 lambda 表达式。

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return MyClass::lambda[=11=];
}

private synthetic void lambda[=11=](String... args) {
    coco();
    String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
    System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
}

你也可以定义一个CommandLineRunner的实现,但是它会打印“运行”而不是commandLineRunner,但是作为之前解决方案的一个优点,“运行”每次都会打印commandLineRunner 被调用,而且不仅在创建 bean 时调用一次,恕我直言,我认为这更有用

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return new CommandLineRunner() {
        public void run(String... args) throws Exception {
            String strCurrMethodName = new Object() {
            }.getClass().getEnclosingMethod().getName();
            System.out.println(strCurrMethodName);
        }
    };
}