基于Spring java的配置ResourceLoader

时间:2014-08-14 14:59:39

标签: spring-mvc

我是Spring的基于java的配置新手。我正在尝试转换此处的基于xml的配置:https://github.com/sps/mustache-spring-view

我的问题是MustacheViewResolver使用的ResourceLoader抛出空指针异常。如何将spring提供的资源加载器正确加载到此配置中?

@Configuration
@ComponentScan(basePackageClasses = Application.class, includeFilters = @Filter(Controller.class), useDefaultFilters = false)
class WebMvcConfig extends WebMvcConfigurationSupport {
    @Bean
    public MustacheViewResolver viewResolver() {
        MustacheViewResolver resolver = new MustacheViewResolver();
        resolver.setPrefix("/WEB-INF/views/mustache/");
        resolver.setSuffix("hbs");
        resolver.setCache(true);

        resolver.setTemplateFactory(new MustacheJTemplateFactory());
        return resolver;
    }
}

例外:

Caused by: java.lang.NullPointerException
    at org.springframework.web.servlet.view.mustache.java.MustacheJTemplateFactory.getReader(MustacheJTemplateFactory.java:71)

来自MustacheJTemplateFactory的行

Resource resource = resourceLoader.getResource(resourceName);

请注意:我认为这是关于spring java配置的一般性问题,而不是关于我正在使用的库的具体问题。我可能错了!

1 个答案:

答案 0 :(得分:1)

在Spring资源加载器中自动装配:

@Autowired
ResourceLoader resourceLoader;

然后在viewResolver()函数中设置它:

MustacheJTemplateFactory factory = new MustacheJTemplateFactory();
factory.setResourceLoader(resourceLoader);
resolver.setTemplateFactory(factory);