用的是springboot最新的穩定版本,在使用自定義localResolver實現國際化時,出現了錯誤,參照網上的文章,發現並不生效
未實現頁面按照請求參數的值來顯示中文還是英文,出現這種問題進行了以下排錯:
1.首先想到的是忘記寫注解,經檢查並沒有存在類似問題
2.可能存在添加注解的時候import包出現問題,經檢查也沒有存在類似問題
3.可能是自己的邏輯有些混亂,於是重新梳理自己的代碼邏輯,最后檢查也沒有錯誤
4.實在找不到什么原因了,最后決定看看官方文檔,畢竟網上的很多解答可以追述到官方文檔中
在WebMvcAutoConfiguration里邊自動配置的localeResolver,可以清楚的看到如下代碼如果自己定義了localeResolver加載自己的,否則加載系統的
public LocaleResolver localeResolver() { if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) { return new FixedLocaleResolver(this.mvcProperties.getLocale()); } else { AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); localeResolver.setDefaultLocale(this.mvcProperties.getLocale()); return localeResolver; } }
在《Spring Boot 2 Recipes: A Problem-Solution Approach》書中提到這樣一句話:
You can also define a locale resolver by registering a bean of type LocaleResolver in the web application context.
You must set the bean name of the locale resolver to localeResolver so it can be autodetected.
上述英語意思為:在自定義localeResolver時方法名必須一致,檢查自己的發現確實不對
改過后方法名的如下
大致一看沒有問題,但細看確實是方法名拼寫錯誤,改過來即可實現國際化
總結:以后遇到這種情況情況少,但仍需注意,注意書寫!