下面是我的课中,我不得不同时使用@Configuration,并@Controller作为应该只有一个实例Thymeleaf在整个应用程序一样,我得到的例外。我的其他类被注释,@RequestScope所以我不能使用单例作用域 bean。所以我混合了配置和控制器来得到结果,但我觉得这是一个不好的做法。我将不胜感激任何重构代码和消除不良做法的帮助。更新我正在使用spring-boot 1.5.14. 我使用以下方法来处理模板并将处理后的模板保留为字符串。@Controller@Configuration@EnableWebMvc@ApplicationScopepublic class MyThymeleafConfig { @GetMapping("/view-template") @ResponseBody public void viewTemplates() { Context context = new Context(); context.setVariable("mydata", "this is it"); String html = templateEngine().process("templates/view-to-process.html", context); System.out.println(html); } /* configuration for thymeleaf and template processing */ @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(thymeleafTemplateResolver()); return templateEngine; } @Bean public SpringResourceTemplateResolver thymeleafTemplateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("classpath:"); templateResolver.setSuffix(".html"); templateResolver.setCacheable(false); templateResolver.setTemplateMode(TemplateMode.HTML); return templateResolver; } @Bean public ThymeleafViewResolver thymeleafViewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; }}要提供静态资源,请使用以下配置:@Configuration@EnableWebMvcpublic class StaticResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/**") .addResourceLocations("/static/", "classpath:static/"); }}更新我还提到了我不能接受下面提到的答案的原因,因为我的其他类有请求范围。
3 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
假设您使用的是 Spring Boot,因为您在标签中有它,所以您不需要任何配置即可使用 Thymeleaf。
只需拥有此依赖项,您就可以:
@GetMapping("/view-template")
public String viewTemplates(Model model) {
model.addAttribute("mydata", "this is it")
return "view-to-process";
}
它应该工作。
顺便说一句,是的,在同一个课堂上拥有@Configuration和@Controller是您永远不需要的东西。
阿波罗的战车
TA贡献1862条经验 获得超6个赞
看一下 Spring Boot 文档的典型布局
还有这篇文章SOLID 编程原理
并查看 Spring Boot 指南Spring Boot Thymeleaf(您不需要@Bean 配置)
简而言之,您应该将
1.MyThymeleafConfig
配置
2.TemplateController
与viewTemplates()
另一个端点分开
添加回答
举报
0/150
提交
取消