Spring Boot如何查找controller包?index.html默认页是如何配置的?
Spring Boot 问题解答
1. SpringApplication.run 找到controller包的原理
启动类上的@SpringBootApplication是复合注解,其中包含@ComponentScan注解,该注解的默认扫描规则为:
- 若未显式指定扫描路径,会自动扫描标注了@SpringBootApplication的启动类所在的包,以及该包下的所有子包
- 只要你的controller包属于启动类所在包的子包,包下标注了
@Controller、@RestController、@Service、@Component等注解的类都会被Spring自动扫描识别,加载到IOC容器中
如果你的controller包不在启动类的同级/子包路径下,可以手动指定扫描路径:
@SpringBootApplication(scanBasePackages = "你的controller包全路径") public class PayApplication { public static void main(String[] args) { SpringApplication.run(PayrollApplication.class, args); } }
2. index.html被设置为默认访问页的原因
有两层机制共同作用:
- Spring Boot 内置欢迎页自动配置:Spring Boot 自动配置类
WelcomePageHandlerMapping会默认遍历所有静态资源目录(classpath:/META-INF/resources/、classpath:/resources/、classpath:/static/、classpath:/public/)、模板根目录(引入模板引擎后classpath:/template/会被自动识别为模板根路径)下的index.html文件,找到后会自动将应用根路径/的请求映射到该文件,无需额外配置 - 你当前项目的控制器显式映射:你的
LoginController中显式配置了@GetMapping("/"),如果该接口的返回值为index,结合模板引擎的自动配置规则,会直接匹配到template目录下的index.html返回,该映射优先级高于自动配置的欢迎页
内容的提问来源于stack exchange,提问作者kk luo
相关产品推荐
相关产品推荐

