pom添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
-
spring-boot-starter-web
是开发web项目必须依赖,集成了SpringMVC
和Tomcat
; - 版本号不用写,
parent
项目有统一管理其版本号;
程序入口,启动类
在一级包路径下,比如com.bkwl
,新建一个Application.java
package com.bkwl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication()
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
添加配置文件
在项目resources
目录下新建application.yml
文件(或application.properties
文件),
Spring Boot默认会读取该配置文件。
server:
port: 8080
context-path: /test
#2.0.0版本上下文路径
#servlet:
# context-path: /test
测试验证一下
- 编写一个
Controller
- 运行
Application.java
的main
方法 - 打开浏览器访问
localhost:8080/test/hello
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot";
}
}

注解介绍
-
@SpringBootApplication
-
@SpringBootApplication
是一个复合注解,包括@SpringBootConfiguration
,
@EnableAutoConfiguration
和@ComponentScan
。 -
@SpringBootConfiguration
继承自@Configuration
,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean
注解标记的方法的实例纳入到Spring容器中,并且实例名就是方法名。 -
@EnableAutoConfiguration
的作用是启动自动装配功能。启动后,Spring Boot会根据你添加的jar
包来帮你做默认配置,比如spring-boot-starter-web
,你若不做额外配置,就会自动的按默认配置帮你配置SpringMVC
和Tomcat
。 -
@ComponentScan
的作用是扫描当前包及其子包下被@Component
,@Controller
,@Service
,@Repository
等注解标记的类并纳入到Spring容器中进行管理。与XML配置的<context:component-scan>
功能等同。
-
-
@RestController
相当于@ResponseBody
+@Controller
合在一起的作用。 -
@GetMapping
是一个组合注解,@RequestMapping(method = RequestMethod.GET)
的缩写。同类型的还有@PostMapping
、@PutMapping
、@DeleteMapping
和@PatchMapping
。
网友评论