Initialize default Locale and Timezone with Spring configuration

前端 未结 4 2121
抹茶落季
抹茶落季 2020-12-30 05:36

I\'m loading application settings such as JDBC connection info from a properties file using PropertyPlaceholderConfigurer. I\'d like to also have other settings

4条回答
  •  青春惊慌失措
    2020-12-30 06:01

    It may make sense to ensure that these are set before any beans are processed or initialized, as any beans created before this code is run could end up using the previous system default values. If you are using Spring Boot, you could do this in the main method before even initializing Spring:

    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            Locale.setDefault(Locale.US);
            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
    
            SpringApplication.run(Application.class, args);
        }
    }
    

    If this needs to be run as part of a context that doesn't call the main method, e.g. in a JUnit integration test, you would need to make sure that it's called:

    @SpringBootTest
    public class ApplicationTest {
        @BeforeClass
        public static void initializeLocaleAndTimeZone() {
            // These could be moved into a separate static method in
            // Application.java, to be called in both locations
            Locale.setDefault(Locale.US);
            TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
        }
    
        @Test
        public void applicationStartsUpSuccessfully() {
        }
    }
    

提交回复
热议问题