Java Springbean方法:如何获取方法名?

Java Springbean方法:如何获取方法名?,java,spring,generics,methods,javabeans,Java,Spring,Generics,Methods,Javabeans,假设我有一个java方法,它是用@Bean注释的spring 例如: public void coco() { String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName(); System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;

假设我有一个java方法,它是用@Bean注释的spring

例如:

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:“可可”

Méthode:“lambda$0”

如您所见,我们可以为非bean方法获取方法名。 但是对于bean方法,我们没有设置方法名,而是设置一个由spring管理的通用值(我们得到的是“lambda$0”,而不是“commandLineRunner”)

有没有人有办法获得Springbean方法的名称


提前感谢

将获取方法名称的语句移到lambda表达式之外:

@Bean
公共命令行运行程序命令行运行程序(ApplicationContext ctx){
字符串strCurrMethodName=新对象(){}.getClass().getEnclosuringMethod().getName();
返回args->{coco();
System.out.println(“Méthode:\”“+strcurmethodname+”\”;
};
}

无法从lambda表达式内部执行此操作的原因是,
commandLineRunner
方法在代码运行时早已消失,因为编译器将lambda块转换为隐藏(合成)方法,并使用对该方法的引用替换lambda表达式

@Bean
公共命令行运行程序命令行运行程序(ApplicationContext ctx){
返回MyClass::lambda$0;
}
私有合成无效lambda$0(字符串…参数){
可可();
字符串strCurrMethodName=新对象(){}.getClass().getEnclosuringMethod().getName();
System.out.println(“Méthode:\”“+strcurmethodname+”\”;
}

您也可以定义CommandLineRunner的实现,但它将打印“run”而不是CommandLineRunner,但作为previos解决方案的一个优点,每次调用CommandLineRunner时,都会打印“run”,而不仅仅是创建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);
        }
    };
}

你为什么想要方法名?好吧!这很有道理。我应该多想想。非常感谢Andreas。