【问题标题】:How does Spring Boot RestController works without SpringBootApplication?Spring Boot RestController 在没有 SpringBootApplication 的情况下如何工作?
【发布时间】:2020-10-21 17:55:09
【问题描述】:

在我的项目中,我使用了带有注解的@Configuration、@EnableAutoConfiguration、@ComponentScan 和 ImportResource 配置。我没有使用@SpringBootApplication,但应用程序在没有@SpringBootApplication 注解的情况下成功构建。我不明白为什么没有调用@RestController 类?

    @Configuration
@EnableAutoConfiguration(exclude = {
        //removed default db config
        DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class})
@ComponentScan(basePackages = { "com.test.debasish.dummy" }, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = Test.class))})
@ImportResource( value = {"classpath*:*beans*.xml"})
public class TestApplication{
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}



@RestController
public class TestController {
  private static final String template = "Hello, %s!";
  private final AtomicLong counter = new AtomicLong();


  @GetMapping("/test")
  @ResponseBody
  public Greeting getResource(@RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
    
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
  }

}

【问题讨论】:

  • 请阅读sping boot架构更多细节

标签: spring-boot rest spring-mvc spring-security spring-boot-actuator


【解决方案1】:

您需要设置spring-webmvc 才能使用@RestController

通常使用spring-boot-starter-web自动完成。

更多细节:

如果你想完全控制 Spring MVC,你可以添加自己的 @Configuration 并使用 @EnableWebMvc 注释,或者添加自己的 @Configuration-annotated DelegatingWebMvcConfiguration,如 @EnableWebMvc 的 Javadoc 中所述。

【讨论】:

    【解决方案2】:

    之所以有效,是因为@springbootapplication 注解也包含@Configuration,
    @EnableAutoConfiguration、@ComponentScan 注解。见下图

    https://i.stack.imgur.com/PKkb8.jpg

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 2020-04-03
      • 2016-01-22
      • 2015-08-03
      • 2017-07-22
      • 2019-03-17
      • 2020-12-23
      • 2020-12-20
      相关资源
      最近更新 更多