Inject a file resource into Spring bean

后端 未结 3 1518
离开以前
离开以前 2021-01-12 09:56

What is a good way to inject some file resource into Spring bean ? Now i autowire ServletContext and use like below. Is more elegant way to do that in Spring MVC ?



        
3条回答
  •  盖世英雄少女心
    2021-01-12 10:18

    What do you intend to use the resource for? In you example you don't do anything with it.

    From it's name, however, it looks like you are trying to load internationalisation / localisation messages - for which you can you a MessageSource.

    If you define some beans (possibly in a separate messages-context.xml) similar to this:

    
        
            
                WEB-INF/messages/messages
            
        
    
    
    
        
    
    
    
        
    
    

    Spring will load your resource bundle when you application starts. You can then autowire the MessageSource into your controller and use it to get localised messages:

    @Controller
    public class SomeController {
    
        @Autowired
        private MessageSource messageSource;
    
        @RequestMapping("/texts")
        public ModelAndView texts(Locale locale) {
            String localisedMessage = messageSource.getMessage("my.message.key", new Object[]{}, locale)
            /* do something with localised message here */
            return new ModelAndView("texts");
        }
    }
    

    NB. adding Locale as a parameter to your controller method will cause Spring to magically wire it in - that's all you need to do.

    You can also then access the messages in your resource bundle in your JSPs using:

    
    

    Which is my preferred way to do it - just seems cleaner.

提交回复
热议问题