我正在使用Velocity模板和Spring启动。
当模板目录中有一个名为'xxx.vm'的文件时,Spring Boot 会成功加载'xxx.vm'。但会记录下面的错误消息。
“ERROR org.apache.velocity:ResourceManager:无法在任何资源加载器中找到资源'xxx.html.vm'。”
我不明白为什么系统会查找'xxx.html.vm',因为application.properties中的后缀设置为“.vm”
这是application.properties
中的配置spring.velocity.enabled=true
spring.velocity.resource-loader-path=classpath:/templates/
spring.velocity.suffix=.vm
运行我的应用程序没有问题, 但我想知道导致此错误消息的原因。 你能帮我解决这个问题吗?提前谢谢。
答案 0 :(得分:3)
将以下行添加到application.properties
:
spring.velocity.view-names=xxx,yyy,zzz
答案 1 :(得分:1)
这是因为spring boot根据类路径中的可用内容配置各种ViewResolvers 如果在类路径中找到了速度依赖性,那么spring将配置一个VelocityViewResolver,但同时它也配置其他视图解析器,ContentNegotiatingViewResolver就是其中之一。
ContentNegotiatingViewResolver尝试匹配视图名称和MIME类型,以自动确定最佳视图。在此过程中,它会尝试查找XXX.vm.html,从而抛出异常。
要解决此问题,请手动配置视图解析程序。 请参阅:http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-switch-off-default-mvc-configuration
我通过引入以下类来手动配置我的viewResolvers,问题就消失了。
@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
@Autowired
private final ResourceLoader resourceLoader = new DefaultResourceLoader();
@Bean
public VelocityConfig velocityConfig() {
VelocityConfigurer cfg = new VelocityConfigurer();
cfg.setResourceLoader(resourceLoader);
cfg.setResourceLoaderPath("classpath:/templates/")
return cfg;
}
@Bean
public ViewResolver viewResolver() {
VelocityViewResolver resolver = new VelocityViewResolver();
resolver.setViewClass(VelocityToolboxView.class);
resolver.setPrefix("");
resolver.setSuffix(".vm");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
final String[] CLASSPATH_RESOURCE_LOCATIONS = [
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" ];
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}
}
答案 2 :(得分:0)
@Sujit Kamthe之所以说完全正确。我有同样的错误并通过在WebConfig类中手动配置“ContentNegotiationConfigurer”来修复它。
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
favorParameter(false).
ignoreAcceptHeader(false).
useJaf(false).
defaultContentType(MediaType.TEXT_HTML).
mediaType("json", MediaType.APPLICATION_JSON);
}
}
Refer:https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc