Initialize default Locale and Timezone with Spring

2019-02-04 15:38发布

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.

3条回答
ゆ 、 Hurt°
2楼-- · 2019-02-04 16:13

I've used a ServletContextListener. In contextInitialized(..) TimeZone.setDefault(..) is called.

It won't be taken into account if you rely on the timezone in any constructor or @PostConstruct / afterPropertiesSet() though.

If you need it, take a look at this question

查看更多
戒情不戒烟
3楼-- · 2019-02-04 16:15

How about standalone spring boot application? The java application looks like:

@SpringBootApplication
@EnableScheduling
@EnableConfigurationProperties(TaskProperty.class)
public class JobApplication {

/*  @Autowired
    private TaskProperty taskProperty;
*/  
    public static void main(String[] args) {
        SpringApplication.run(JobApplication.class, args);
    }
} 
查看更多
手持菜刀,她持情操
4楼-- · 2019-02-04 16:36

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

    }

}
查看更多
登录 后发表回答