0

I'm learning Spring Boot recently, But I'm quite confused by @Bean annotation and @Component annotation.

Now I want to change the page language by clicking on language buttons. So I create a LocaleResolver:

public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String lang = httpServletRequest.getParameter("lang"); 
        Locale locale = Locale.getDefault(); 
        if(lang != null && lang.length() !=0){ 
            String[] splitted = lang.split("-");
            locale = new Locale(splitted[0], splitted[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {}
}

And in the configuration class MyMvcConfig:

@Configuration
public class MyMvcConfig {
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

And it works properly, my own implementation replaces the default LocaleResolver in WebMvcAutoConfiguraion. But if I remove the configuration class and add @Component annotation to MyLocaleResolver class, then the container will still use the default LocaleResolver. Why this happen?

Virgil Chen
  • 53
  • 1
  • 5

0 Answers0