spring boot(1) 快速开始第一个spring boot应用

开发环境:jdk1.8,maven 3.2+

简介

spring boot 可以让我们在写很少的spring 配置和依赖的情况下,简单快速地开发基于spring 的应用。

第一个spring boot应用

实现的功能很简单,访问localhost:8080,返回hello world界面

项目的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>win.yanfan.study</groupId>
    <artifactId>spring-boot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

** 简单说明 **

  1. parent pom 定义为spring-boot-starter-parent,它会为我们添加spring-boot需要的一些核心依赖,并可以对所有的相关spring-boot-starter做统一的version管理(后面添加starter依赖,不用写版本号)
  2. 因为我们要开始一个简单的web应用,所以在dependencies 中添加spring-boot-starter-web依赖,它会帮我们添加spring-web开发相关的依赖


  3. plugin spring-boot-maven-plugin让我们的项目编译后生成一个可执行的jar

代码

代码很简单
@RestController,@RequestMapping("/")都是spring-mvc中的注解
@EnableAutoConfiguration 告诉spring-boot如何配置我们添加的相关依赖

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

运行

直接在项目中运行mvn spring-boot:run,或者直接在idea里点run就行了

运行结果

下面是对starters的介绍,可以根据自己需要开发的应用类型选择合适的starter

starters

spring-boot提供了一系列spring-boot-starter-*形式的starters,这些starters定义了对一系列特定应用开发所需的spring相关的依赖集合。我们只需要添加对相应的starters的依赖,就可以快速开发对应类型的spring应用。
比如我们在前文开发web应用添加的spring-boot-starter-web依赖,它会添加对应的web相关依赖
主要starters和其对应的应用类型介绍

starts详细介绍链接http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容