美文网首页
Spring Boot搭建Web项目

Spring Boot搭建Web项目

作者: Xiewb | 来源:发表于2019-04-27 21:09 被阅读0次

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项目必须依赖,集成了SpringMVCTomcat
  • 版本号不用写,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.javamain方法
  • 打开浏览器访问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";
    }
}
看到这个,恭喜你成功了!

注解介绍

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

相关文章

网友评论

      本文标题:Spring Boot搭建Web项目

      本文链接:https://www.haomeiwen.com/subject/fvhlnqtx.html