Override Spring:message tag with database values

后端 未结 3 1973
小蘑菇
小蘑菇 2020-12-09 12:38

I am using Spring to display messages from a properties file. I would like to be able to override the tag to use a value from a database

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 13:18

    I ended up creating a class called DatabaseMessageSource included below. I still need to implement some kind of caching so I don't hit the database with each call. This link was helpful too. Thank you skaffman and PrimosK for pointing me in the right direction.

    public class DatabaseMessageSource extends ReloadableResourceBundleMessageSource {
    
        @Autowired
        private MyDao myDao;
    
    
        protected MessageFormat resolveCode(String code, Locale locale) {
    
            MyObj myObj = myDao.findByCode(code);
    
            MessageFormat format;
    
            if (myObj!= null && myObj.getId() != null) {
    
                format = new MessageFormat(myObj.getValue(), locale);
    
            } else {
    
                format = super.resolveCode(code, locale);
    
            }
    
            return format;
    
        }
    
        protected String resolveCodeWithoutArguments(String code, Locale locale) {
    
            MyObj myObj = myDao.findByCode(code);
    
            String format;
    
            if (myObj != null && myObj.getId() != null) {
    
                format = myObj.getValue();
    
            } else {
    
                format = super.resolveCodeWithoutArguments(code, locale);
    
            }
    
            return format;
    
        }
    
    }
    

    I updated my applicationContext to point to the newly created class. I changed it to:

    
        
            
                classpath:defaultMessages
            
        
            
    `enter code here`
    

提交回复
热议问题