当前位置: 首页 > 知识库问答 >
问题:

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

暨成双
2023-03-14

下面是我的类,我必须同时使用配置和控制器,因为整个应用程序中应该只有一个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/");
    }
}

更新

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

更新

我还有其他类与RequestScope一起使用,如下所示:

@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";
    }
}

共有3个答案

司空祯
2023-03-14

查看Spring Boot文档典型布局

此外,本文还介绍了固体编程原理

查看Spring Boot guide Spring Boot Thymeleaf(您不需要@Bean配置)

用两个词您应该将
1.MyThymeleafConfig配置
2.TemplateControllerviewTemboard()和另一个endpoint分开

孟思远
2023-03-14

如果您看到注释(Spring 5)的源代码,那么您有:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any (or empty String otherwise)
     */
    @AliasFor(annotation = Component.class)
    String value() default "";

}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

    /**
     * Explicitly specify the name of the Spring bean definition associated
     * with this Configuration class. If left unspecified (the common case),
     * a bean name will be automatically generated.
     * <p>The custom name applies only if the Configuration class is picked up via
     * component scanning or supplied directly to a {@link AnnotationConfigApplicationContext}.
     * If the Configuration class is registered as a traditional XML bean definition,
     * the name/id of the bean element will take precedence.
     * @return the suggested component name, if any (or empty String otherwise)
     * @see org.springframework.beans.factory.support.DefaultBeanNameGenerator
     */
    @AliasFor(annotation = Component.class)
    String value() default "";
}

您注意到它们是相同的(它们都包括更通用的组件注释)。因此,看到这一事实就把它们都用在一起是没有意义的。另一件更重要的事情是,spring试图为这些注释提供一种标签含义,以描述其用途。

配置用于将必要的部分连接到应用程序,以便在启动阶段正常运行。

控制器用来定义一个作为外部世界接口的类,即:其他参与者如何使用您的应用程序。

如您所见,将这两个一起使用几乎没有意义。

公孙俊弼
2023-03-14

假设您使用的是Spring Boot,因为您在标签中有它,所以您不需要任何配置就可以使用Thymeleaf。

通过使用此依赖项,您可以:

@GetMapping("/view-template")
public String viewTemplates(Model model) {
    model.addAttribute("mydata", "this is it")
    return "view-to-process";
}

它应该会起作用。

顺便说一句,是的,在同一个类中拥有@Configuration@Controller是您永远不需要的东西。

 类似资料:
  • 我正在学习Spring框架,但我不能理解注释的确切含义以及应该对哪些类进行注释。在Spring Boot文档中,说应用程序类应该是class。 Spring Boot支持基于Java的配置。虽然可以使用XML源调用SpringApplication.run(),但我们通常建议您的主要源是@Configuration类。 在尝试了解时,我发现用注释类表明Spring IoC容器可以使用该类作为bea

  • 这些是实现控制器类 然而,当我们在Spring MVC程序中使用@Controller注释时,如何知道我们的@Controller注释正在实现这些控制器中的任何一个

  • Spring参考文档说明如下: ComponentScanPackageMarker类故意省略了@Configuration注释。我已经测试了组件扫描和自动连接功能。令我吃惊的是,一切都很顺利: 组件扫描的这种行为是故意的吗?为什么即使没有@Configuration注释也能工作?

  • 我使用的是Spring 3.1。War不是使用Maven构建的。这只是一个正常的构建。我的课程路径中有以下罐子。 我有下面的代码, 当我运行方法时,我得到下面的异常 为了克服这个问题,如果我添加,会出现以下异常。 为了克服这个问题,如果我添加,就会出现以下异常。 如何克服我最初的异常-

  • 我有一些服务类,它们扩展了带有@Annotation1注解的BaseService类。在@Annotation1中还有另一个注释-@Annotation2。 我希望能够创建aspect方法,它在用@Annotation2注释的类中的所有方法之前运行,所以在任何扩展BaseService类的服务中都是如此。 当我直接在BaseService中应用@AnNotation2时,我可以运行方面方法,或者当

  • 我使用的是改型2.1,当我调用@get时,它会说 现在..如果我定义@retrofit.http.get,它将抛出 以及方法 分级文件