SpringBoot入门之零基础搭建web应用

引言

之前也没有深入学习过spring框架,最近SpringBoot流行起来后想补下这方面的知识,于是照着SpringBoot官网上的英文教程开始helloworld入门,踩到几个小坑,记录下学习流程。

SpringBoot有哪些优点

SpringBoot可以帮助我们快速搭建应用,自动装配缺失的bean,使我们把更多的精力集中在业务开发上而不是基础框架的搭建上。它有但是远不止以下这几点优点:

  • 它有内置的Tomcat和jetty容器,避免了配置容器、部署war包等步骤
  • 能够自动添加缺失的bean
  • 简化了xml配置甚至不需要xml来配置bean

入门准备工作

  • JDK1.8+(JDK1.7也可以,但是官方的例程里用到了一些lambda表达式,lambda表达式只在JDK1.8及以上的版本才支持)
  • MAVEN 3.0+
  • IDE:IDEA (开发工具我选择的是IDEA)

搭建HelloWorld web应用

创建一个空maven工程

使用idea创建maven工程,这里GroupId和artifactId任意指定即可

创建maven工程

我们开始配置pom文件,指定该helloworld的父工程为spring-boot-starter-parent,这样我们就不需要指定SpringBoot的一些相关依赖的版本了(因为在父工程中已指定)。
配置完的pom.xml文件如下:

<?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>org.springframework</groupId>
    <artifactId>helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

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

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

其中spring-boot-maven-plugin插件可以帮助我们在使用mvn package命令打包的时候生成一个可以直接运行的jar文件。(spring-boot-maven-plugin作用)

创建web应用

创建一个controller,目录在src/main/java/hello/HelloController.java

package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RestController
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

    @RequestMapping("/HelloWorld")
    public String hello() {
        return "Hello World!";
    }
}

创建一个web application,目录在src/main/java/hello/HelloController.java

package hello;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    //指定下bean的名称
    @Bean(name = "gzr")
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                System.out.println("Let's inspect the beans provided by Spring Boot:");
                String[] beanNames = ctx.getBeanDefinitionNames();
                for (String beanName : beanNames){
                    System.out.println(beanName);
                }
            }
        };
    }
}

可以看到,我们不需要xml来配置bean,也不需要配置web.xml文件,这是一个纯java应用,我们不需要来处理复杂的配置关系等。

运行应用

可以通过命令行直接运行应用
$ mvn package && java -jar target/helloworld-1.0-SNAPSHOT.jar

当然我更倾向于使用idea来运行,这样可以debug看到SpringBoot的初始化过程,配置过程如下


idea运行app

让我们用idea来debug看看,如果编译时出现“Error:java: Compilation failed: internal java compiler error”的错误(如下图),我们需要修改idea默认的编译器设置


compile错误.png

修改compiler设置如下
compiler修改

我们可以在控制台看到运行结果,截取一段见下图,可以看到打印出的bean,包括helloController、和我们指定名字的gzr等


打印出的bean.png

下面我们来检查web的服务,在命令行运行

$ curl localhost:8080
Greetings from Spring Boot!
$ curl localhost:8080/HelloWorld
Hello World!%

服务正常运行~

添加测试用例

我们先在pom中添加测试需要的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

添加一个简单的测试用例,目录在src/test/java/hello/HelloControllerTest.java

package hello;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }
}

可以很轻松地直接运行该test

至此我们模拟了http请求来进行测试,通过SpringBoot我们也可以编写一个简单的全栈集成测试:
src/test/java/hello/HelloControllerIT.java

package hello;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author zengrong.gzr
 * @Date 2017/03/11
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(),
                String.class);
        assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
    }
}

通过webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT我们可以让内置的服务器在随机端口启动。

添加生产管理服务

通常我们在建设网站的时候,可能需要添加一些管理服务。SpringBoot提供了几个开箱即用的管理服务,如健康检查、dump数据等。
我们首先在pom中添加管理服务需要的依赖

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

直接运行程序,可以看到控制台输出诸多SpringBoot提供的管理服务


SpringBoot提供的管理服务.png

我们可以很方便地检查app的健康状况

$ curl localhost:8080/health
{"status":"UP"}
$ curl localhost:8080/dump
{"timestamp":1489226509796,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource.","path":"/dump"}

当我们执行curl localhost:8080/dump可以看到返回状态为“Unauthorized”,dump、bean等权限需要关闭安全控制才可以访问。那么如何关闭?可以通过注解的方式,也可以通过配置application.properties的方式。

这里我们选择第二种,在src/main/resources文件夹下新建application.properties文件(框架会自动扫描该文件),在文件中添如配置management.security.enabled=false即可。

启动应用后,我们再运行curl localhost:8080/beans命令,可以看到命令行打印出系统加载的所有bean。

源码下载

附上源码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容