Annotated a class with @Configuration and @Controller. Need help in refactoring

前端 未结 6 614
一整个雨季
一整个雨季 2021-01-17 15:49

Below is my class in which i had to use both @Configuration and @Controller as there should be only one instance of Thymeleaf in the e

6条回答
  •  广开言路
    2021-01-17 16:08

    To refactor them, it's easy and straight forward to separate @Bean methods to a separate @Configuration class:

    @Configuration
    // @Controller  is redundant as we have @Configuration
    // @EnableWebMvc is also redundant since you already annotate it in other class
    // @ApplicationScope is also redundant since you do not need to create bean of MyThymeleafConfig anymore
    public class MyThymeleafConfig {
        /*
    
        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 class return the same bean instance, regardless how many times you call the bean methods.

    Now in your controller:

    @Controller
    public class MyThymeleafConfig {
    
        @Autowired
        private SpringTemplateEngine templateEngine;
    
        @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);
        }
    }
    

    But honestly, I don't know why you have to manually interact with TemplateEngine / SpringTemplateEngine, since Spring-thymeleaf will automatically process the template with given variable for you. (Like @sedooe example)

提交回复
热议问题