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。













网友评论