Spring Boot搭建web服务

来源:互联网 发布:win7如何更改mac地址 编辑:程序博客网 时间:2024/05/20 05:29

Spring Boot搭建web服务

1. 介绍

Spring Boot是一个全新的框架,它是一种用来轻松创建具有最小或零配置的独立应用程序的方式,其目的是简化Spring应用的初始搭建以及开发过程。
下面将介绍如何使用Spring Boot搭建web服务。

2. web服务搭建步骤

2.1 Jar包依赖

要使用Spring Boot,需要引入两个依赖,spring-boot-starter-parent 和 spring-boot-starter-web,虽然看上去只有两个依赖,但实际上通过间接依赖将很多相关的内容都已经引入进来了,因此能够简化开发过程。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.4.0.RELEASE</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>swan-boot-web</artifactId>    <packaging>war</packaging>    <name>swan-boot-web</name>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>    </dependencies></project>

2.2 Spring Boot启动类

Spring Boot可以通过IDE的main方法启动,其配置更是简单,一个注解 @SpringBootApplication 和 和一个启动方法SpringApplication.run();

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

@SpringBootApplication 等同于默认的属性 @Configuration, @EnableAutoConfiguration 和 @ComponentScan

  • @Configuration
  • @EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类;
  • @ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean;

SpringApplication 则是用于从main方法启动Spring应用的类。默认会执行以下步骤:

  • 创建一个合适的ApplicationContext实例;
  • 注册一个CommandLinePropertySource,以便将命令行参数作为Spring properties
  • 刷新application context,加载所有单例bean
  • 激活所有CommandLineRunner beans。

2.3 实现Controller

@RestController是一类特殊的@Controller,它的返回值直接作为HTTP Response的Body部分返回给浏览器

@RestControllerpublic class HelloWorld {    @RequestMapping("/hello")    public String hello() {        return "hello,Spring boot!";    }    //带参数    @RequestMapping("/world/{name}")    public String word(@PathVariable String name) {        return "word--spring boot:" + name;    }}

2.4 测试

启动main()函数;
在浏览器输入:http://localhost:8080/hello
返回:hello,Spring boot!
这里写图片描述

原创粉丝点击