用@Configuration 和@Controller 注释一个类。在重构方面需要帮助

下面是我的课中,我不得不同时使用@Configuration,并@Controller作为应该只有一个实例Thymeleaf在整个应用程序一样,我得到的例外。我的其他类被注释,@RequestScope所以我不能使用单例作用域 bean。所以我混合了配置和控制器来得到结果,但我觉得这是一个不好的做法。我将不胜感激任何重构代码和消除不良做法的帮助。


更新


我正在使用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/");

    }

}

更新


我还提到了我不能接受下面提到的答案的原因,因为我的其他类有请求范围。



潇湘沐
浏览 211回答 3
3回答

撒科打诨

假设您使用的是 Spring Boot,因为您在标签中有它,所以您不需要任何配置即可使用 Thymeleaf。只需拥有此依赖项,您就可以:@GetMapping("/view-template")public String viewTemplates(Model model) {    model.addAttribute("mydata", "this is it")    return "view-to-process";}它应该工作。顺便说一句,是的,在同一个课堂上拥有@Configuration和@Controller是您永远不需要的东西。

阿波罗的战车

看一下 Spring Boot 文档的典型布局还有这篇文章SOLID 编程原理并查看 Spring Boot 指南Spring Boot Thymeleaf(您不需要@Bean 配置)简而言之,您应该将1.MyThymeleafConfig配置2.TemplateController与viewTemplates()另一个端点分开
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java