注解与main方法
EnableAutoConfiguration
This
class-level
annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Sincespring-boot-starter-web
addedTomcat
andSpring MVC
, the auto-configuration assumes that you are developing aweb application
andsets up Spring
accordingly.
- 功能:开启自动配置
- 修饰范围:只能用于类
- 实际作用:根据
pom.xml
文件中的依赖(如spring-boot-starter-web
),来构建相关环境(Tomcat
—web容器和Spring MVC
)
ComponentScan
- 作用:开启注解扫描
- 修饰范围:只能用于类
- 扫描范围:当前包及其子包
RestController
This is known as a stereotype annotation. It provides hints for people reading the code and for Spring that the
class plays a specific role
. In this case, our class is a web@Controller
, so Spring considers it when handling incoming web requests.
- 作用:用来实例化当前对象为一个控制器对象,并将类上所有方法的返回值转为
json
,响应给浏览器- 相当于
@Controller
(实例化当前类为一个控制器)与@ResponseBody
(将当前方法返回值转换为json
,响应给浏览器)的组合,支持RESTful
访问方 式,返回结果都是json
字符串。区别见[Controller与RestController区别](# Controller与RestController区别)
- 相当于
- 修饰范围:只能用于类
RequestMapping
The
@RequestMapping
annotation provides “routing” information. It tells Spring that any HTTP request with the/chenzf
path should be mapped to thehello
method. The@RestController
annotation tells Spring to render the resulting string directly back to the caller.
- 作用:用来加入访问路径
- 修饰范围:
类
(加入命名空间)与方法
(指定具体路径) @GetMapping
限定请求方式只能是Get
,并指定路径,可以被RequestMapping
替代,一般只用于修饰方法@PostMapping
、@PutMapping
、@DeleteMapping
类似,也用于限定请求方式
SpringBootApplication
@SpringBootApplication
注解等价于
@SpringBootConfiguration
:标识注解,标识这是一个Spring Boot的配置类@EnableAutoConfiguration
:自动与项目中集成的第三方技术进行集成@ComponentScan
:扫描入口类所在子包以及子包后代包中注解
main方法
SpringApplication.run(Application.class, args);
This is a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s
SpringApplication
class by callingrun
.SpringApplication
bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to passApplication.class
as an argument to therun
method to tellSpringApplication
which is the primary Spring component. Theargs
array is also passed through to expose any command-line arguments.
- 通过标准Java入口方式,委托给
SpringApplication
,并告知当前Spring Boot主应用类是谁,从而启动Spring Boot中Tomcat容器 args
可以在启动时指定外部参数,来覆盖Spring Boot中一些默认配置- 不修改配置文件,在运行时将端口号临时改为9999: