代码地址:
https://gitee.com/better-code/SpringBoot-Example/springboot01_1/
代码结构:
具体代码使用:
com.example.springboot01_1.web.HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
String name = "SpringBoot";
return "Hello "+name+" !";
}
}
com.example.springboot01_1.App
@EnableAutoConfiguration
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Run App.java
访问 http://localhost:8080/hello
,页面报错 Whitelabel Error Page
。
原因:没有将
HelloController
添加到spring容器中
修改 App.java
如下(增加@ComponentScan)
@EnableAutoConfiguration
@ComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Run App.java
访问 http://localhost:8080/hello,页面打印 Hello SpringBoot !
修改 App.java
如下(去掉@EnableAutoConfiguration)
@ComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Run App.java 时,提示错误
ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
总结:
通常建议将应用的main类放到其他类所在包的顶层(root package),并将 @EnableAutoConfiguration 注解到你的main类上,这样就隐式地定义了一个基础的包搜索路径(search package),以搜索某些特定的注解实体(比如@Service,@Component等) 。
例如,如果你正在编写一个JPA应用,Spring将搜索 @EnableAutoConfiguration 注解的类所在包下的 @Entity 实体。采用root package方式,你就可以使用 @ComponentScan 注解而不需要指定 basePackage 属性,也可以使用 @SpringBootApplication 注解,只要将main类放到root package中。
如果@ComponentScan属性basePackages、value为空,则以@ComponentScan注解的类所在的包为基本的扫描路径
@EnableAutoConfiguration 注解只会自动搜索当前注解实体类(原文这里有误,经试验,并不能扫描加载到当前类所在的同包中的类。参看https://blog.csdn.net/HD243608836/article/details/123024204),
而@ComponentScan 会自动搜索当前类所在包的所有子包
下的注解实体类。
@ComponentScan + @EnableAutoConfiguration = @SpringBootApplication
参考自,对原文有纠正:https://www.jianshu.com/p/bcd4b0078d2a