MessageSource doesn't reload properties file

前端 未结 1 1748
名媛妹妹
名媛妹妹 2020-12-22 06:28

There is a messageSource Bean:

@Bean
public MessageSource messageSource(){
    ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBund         


        
相关标签:
1条回答
  • 2020-12-22 07:11

    Try this solution. First: configure the bean in your web configuration as shown below.

    @Bean
    public MessageSource messageSource () {
        ReloadableResourceBundleMessageSourceExt messageResource =
                new ReloadableResourceBundleMessageSourceExt();
        messageResource.setAlwaysUseMessageFormat(false);
        messageResource.setBasenames("classpath:messages");
        messageResource.setDefaultEncoding(CHARACTER_ENCODING);
        messageResource.setFallbackToSystemLocale(true);
        messageResource.setUseCodeAsDefaultMessage(false);
        messageResource.setCacheSeconds(1); // by default it set to -1 which means cache 
                                            // forever messageSourse.
                                            // set 0 to check reload messeageSource on 
                                            // every getMessageSource request but reload 
                                            // only those files which last modified 
                                            // timestamp is changed.
                                            // value greater than 1 is treated as the 
                                            // time interval between reload.
        return messageResource;
    }
    

    Second: create a class which extends ReloadableResourceBundleMessageSource to expose the protected method of its inner class as shown below.

    public class ReloadableResourceBundleMessageSourceExt extends ReloadableResourceBundleMessageSource {
    
    public Properties getPropertiesByFileName(String fileName){
        return super.getProperties(fileName).getProperties();
    }
    

    }

    Third: Now Autowired the bean like this.

    @Service 
    public class MyMessagesBundleService {
    
    final private String fileName = "classpath:messages";
    
    @Autowired
    ReloadableResourceBundleMessageSourceExt messageSource;
    Properties properties = messageSource.getPropertiesByFileName(this.fileName);
    // now change the properties and saved it.
    // after saved call clear cache and get again.
    messageSource.clearCache();
    
    }
    
    0 讨论(0)
提交回复
热议问题