Search code examples
javaspringgenericsmethodsjavabeans

spring bean method : how to get method name?


Let's suppose i have a java method that is spring annotated with @Bean.

Example :

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

Here is the console output :

Méthode : "coco"

Méthode : "lambda$0"

As you can see, we can ideed get the method name for a non bean method. But for a bean method we do not tget the method name but a generic value managed by spring (we get "lambda$0" instead of "commandLineRunner".

Do anyone have a solution to get the name ofthe method for a spring bean ?

Thanks in advance


Solution

  • Move the statement obtaining the method name outside the lambda expression:

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        String strCurrMethodName = new Object(){}.getClass().getEnclosingMethod().getName();
        return args -> {coco();
                        System.out.println("Méthode : \"" + strCurrMethodName +"\"") ;
                        };
    }
    

    The reason it cannot be done from inside the lambda expression, is that the commandLineRunner method is long gone by the time the code runs, since the compiler convert the lambda block into a hidden (synthetic) method, and replaces the lambdas expression with a reference to that method.

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