优化入门程序
優化入門程序
現在工程中只有一個Controller,可以這么玩;那么如果有多個Controller,怎么辦呢?
添加Hello2Controller:
代碼:
package com.learn.springboot.controller;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;@RestController public class Hello2Controller {@GetMapping("show2")public String test(){return "hello Spring Boot2!";}}啟動重新啟動,訪問show2測試,失敗:
難道要在每一個Controller中都添加一個main方法和@EnableAutoConfiguration注解,這樣啟動一個springboot程序也太麻煩了。也無法同時啟動多個Controller,因為每個main方法都監聽8080端口。所以,一個springboot程序應該只有一個springboot的main方法。
所以,springboot程序引入了一個全局的引導類。
2.5.1.添加引導類
通常請求下,我們在一個springboot工程中都會在基包下創建一個引導類,一些springboot的全局注解(@EnableAutoConfiguration注解)以及springboot程序的入口main方法都放在該類中。
在springboot的程序的基包下(引導類和Controller包在同級目錄下),創建TestApplication.class:
內容如下:
@EnableAutoConfiguration public class TestApplication {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);} }并修改HelloController,去掉main方法及@EnableAutoConfiguration:
@RestController public class HelloController {@GetMapping("show")public String test(){return "hello Spring Boot!";} }啟動引導類,訪問show測試:
發現所有的Controller都不能訪問,為什么?
回想以前程序,我們在配置文件中添加了注解掃描,它能掃描指定包下的所有Controller,而現在并沒有。怎么解決——@ComponentScan注解
2.5.2.@ComponentScan
spring框架除了提供配置方式的注解掃描<context:component-scan />,還提供了注解方式的注解掃描@ComponentScan。
在TestApplication.class中,使用@ComponentScan注解:
@EnableAutoConfiguration @ComponentScan public class TestApplication {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}}重新啟動,訪問show或者show2:
我們跟進該注解的源碼,并沒有看到什么特殊的地方。我們查看注釋:
大概的意思:
配置組件掃描的指令。提供了類似與<context:component-scan>標簽的作用
通過basePackageClasses或者basePackages屬性來指定要掃描的包。如果沒有指定這些屬性,那么將從聲明這個注解的類所在的包開始,掃描包及子包
而我們的@ComponentScan注解聲明的類就是main函數所在的啟動類,因此掃描的包是該類所在包及其子包。一般啟動類會放在一個比較淺的包目錄中。
總結
- 上一篇: SpringBoot整合RocketMQ
- 下一篇: springboot属性注入