I'm loading application settings such as JDBC connection info from a properties file using PropertyPlaceholderConfigurer
. I'd like to also have other settings such as default locale and timezone as properties.
But I'm unsure of the best method to execute Locale.setDefault()
and TimeZone.setDefault()
. I want them run early in startup and only once. Is there a proper way in Spring to execute some code FIRST, before other code is executed? Any suggestions?
I know I can specify default values on the command line, but this application will get installed in many places and I want to avoid problems caused by someone forgetting to specify -Duser.timezone=UTC
or whatever.
While run any application in JVM, JVM will take system default time zone. For example production server is running under PST timezone and spring boot application will start then application will take PST timezone by default.
If you really want to do it yourself use the RequestContextUtils. getTimeZone(request) method. @RequestMapping public String foo(HttpServletRequest request) { TimeZone timezone = RequestContextUtils. getTimeZone(request); ... }
You can explicitly set a default time zone on the command line by using the Java system property called user. timezone . This bypasses the settings in the Windows operating system and can be a workaround.
I found Spring loads some of its default beans including other beans before calling the contextInitialized method, so, here is a better approach "draft" that I can think of, let me know if you see any concern:
public class SystemPropertyDefaultsInitializer
implements WebApplicationInitializer{
private static final Logger logger = Logger
.getLogger(SystemPropertyDefaultsInitializer.class);
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
logger.info("SystemPropertyWebApplicationInitializer onStartup called");
// can be set runtime before Spring instantiates any beans
// TimeZone.setDefault(TimeZone.getTimeZone("GMT+00:00"));
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// cannot override encoding in Spring at runtime as some strings have already been read
// however, we can assert and ensure right values are loaded here
// verify system property is set
Assert.isTrue("UTF-8".equals(System.getProperty("file.encoding")));
// and actually verify it is being used
Charset charset = Charset.defaultCharset();
Assert.isTrue(charset.equals(Charset.forName("UTF-8")));
// locale
// set and verify language
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With