Spring: Does a method name in @Configuration class have any role

Moha the almighty camel :
@Configuration
public class AppConfig implements WebMvcConfigurer {

    // ...

    @Bean
    public LocaleResolver localeResolver(){ // other names for this method didn't work
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

}

Above is a part of my configuration class in a Spring MVC app.

When first testing SessionLocalResolver, I had the method name as localResolver (note the missing E) which caused the following exception: Cannot change HTTP accept header – use a different locale resolution strategy

My understanding, and obviously I was wrong, that the name of bean methods have no semantic value what so ever. But in this case, using any name other than localeResolver results in the above mentioned exceptions.

So my question: what is the role of the bean method name in an @Configuration class ? and where is that mentioned in the Spring documentation ?

nsnan9 :

This specific bean is looked up by name not type. DispatcherServlet looks for a bean named localeResolver and if it's not detected, it uses the default which is AcceptHeaderLocaleResolver. If you wanted to keep your original method name localResolver, you would just need to annotate it as

@Bean (name = "localeResolver")
public LocaleResolver localResolver() {...}

By default, a bean method name will be used as the bean name unless otherwise stated in the manner I presented above. In other words, the bean method name role is used to define the actual bean name. Hope this helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16648&siteId=1