简体   繁体   中英

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

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

you can also define an implementation of CommandLineRunner, but it will print "run" instead of commandLineRunner, but as an advantage of the previos solution, "run" will be printed every time the commandLineRunner is invoked and not only once when the bean was created, which imho i think is more useful

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM