java-用@Configuration和@Controller注释一个类.在重构方面需要帮助
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-用@Configuration和@Controller注释一个类.在重构方面需要帮助,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2575字,纯文字阅读大概需要4分钟。
内容图文
![java-用@Configuration和@Controller注释一个类.在重构方面需要帮助](/upload/InfoBanner/zyjiaocheng/694/d0412cbf071a458cbe2bf4249975dfa9.jpg)
下面是我的类,其中我必须同时使用@Configuration和@Controller,因为在整个应用程序中应该只有Thymeleaf的一个实例,否则我会得到例外.我的其他类都用@RequestScope注释,因此我不能使用单例作用域的bean.所以我混合使用Configuration和Controller来获得结果,但是我觉得这是一个不好的做法.我希望能对重构代码和消除不良做法提供任何帮助.
UPDATE
我正在使用spring-boot 1.5.14.我正在使用以下方法来处理模板,并将处理后的模板保留为字符串.
@Controller
@Configuration
@EnableWebMvc
@ApplicationScope
public 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
@EnableWebMvc
public class StaticResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("/static/", "classpath:static/");
}
}
UPDATE
我还提到了我不能接受以下提到的答案的原因,因为我的其他班级都有请求范围.
UPDATE
我还有@RequestScopelike这样的其他类:
@RequestScope
@Controller
public class SecondController {
@GetMapping("/viewPage")
public String viewPage(Model model) {
model.addAttribute("mydata", "sjfbsdf");
model.addAttribute("somedata", "sjdfksfjhshgdfbskdfj");
return "templates/view-to-process.html";
}
}
解决方法:
假设您正在使用Spring Boot,因为您已将其包含在标签中,所以不需要任何配置即可使用Thymeleaf.
只有this dependency,您可以:
@GetMapping("/view-template")
public String viewTemplates(Model model) {
model.addAttribute("mydata", "this is it")
return "view-to-process";
}
它应该工作.
顺便说一句,是的,您永远都不需要在同一类中使用@Configuration和@Controller.
内容总结
以上是互联网集市为您收集整理的java-用@Configuration和@Controller注释一个类.在重构方面需要帮助全部内容,希望文章能够帮你解决java-用@Configuration和@Controller注释一个类.在重构方面需要帮助所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。