Spring MVC - Customizing ResourceBundleThemeSource by Registering it as a Bean

[Updated: Jan 11, 2018, Created: Jan 11, 2018]

Following example shows how to register a custom ThemeSource. We are still going to use the default ResourceBundleThemeSource but we are going to specify a non-empty base name prefix with it.

Example

Java Config class

UiApplicationContextUtils.initThemeSource() looks for user configured ThemeSource bean by a specific name as defined by UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME before falling back to the default one.

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

  @Bean(UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME)
  public ThemeSource customResourceBundleThemeSource() {
      ResourceBundleThemeSource source = new ResourceBundleThemeSource();
      source.setBasenamePrefix("app_");
      return source;
  }

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
      //mapping '/' to index view name without a controller
      ViewControllerRegistration r = registry.addViewController("/");
      r.setViewName("index");
  }

  @Override
  public void configureViewResolvers(ViewResolverRegistry registry) {
      registry.jsp();//default prefix=/WEB-INF/", suffix=".jsp"
  }
}

Theme Properties files

src/main/resources/app_theme.properties

background=beige
content-style=width:500px;border:solid 2px blue;margin:auto;padding:30px;

src/main/resources/app_theme_fr_FR.properties

background=darkBlue 
content-style=width:500px;border:solid 2px white;color:white;margin:auto;padding:30px;

JSP View:

/src/main/webapp/WEB-INF/index.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<body style="background-color:<spring:theme code='background'/>;">
<div style="<spring:theme code='content-style'/>">
  Test Content
</div>
</body>
</html>

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

From browser with default locale of 'en-US':

Using Postman with an explicit 'Accept-Language' header value of 'fr-FR':

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Custom ResourceBundleThemeSource Example Select All Download
  • resource-bundle-theme-source-customized
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
        • webapp
          • WEB-INF

See Also