Spring Boot入门

2017-08-31  本文已影响38人  自然V简单

最近准备学习下Web开发,发现Spring Boot简化了Spring MVC和其它框架的整合,所以整理下。还是采用小步快跑的方式,不容易出错,而且好上手。最重要的是有问题好找原因好解决。

1. 打开https://start.spring.io,生成项目的基础架构,可以根据自己需要,灵活选择如下内容:maven、gradle、java、groovy、kotlin。

2.一个经典的Hello World入门gradle配置。

buildscript {

ext {

springBootVersion ='1.5.6.RELEASE'

}

repositories {

mavenCentral()

}

dependencies {

classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")

}

}

applyplugin:'java'

applyplugin:'eclipse-wtp'

applyplugin:'idea'

applyplugin:'org.springframework.boot'

applyplugin:'war'

version='0.0.1-SNAPSHOT'

sourceCompatibility=1.8

targetCompatibility=1.8

repositories {

mavenCentral()

}

configurations {

providedRuntime

}

dependencies {

compile('org.springframework.boot:spring-boot-starter-actuator')

compile('org.springframework.boot:spring-boot-starter-web')

runtime('org.springframework.boot:spring-boot-devtools')

testCompile('org.springframework.boot:spring-boot-starter-test')

}

3. 有了基础架构,就转到开发工具了,没必要使用记事本,推荐使用IntelJ Idea

打开Idea,选择Import Project,选择Gradle,基本默认就好。

4. Index World代码

packageorg.penguin.study.boot.gbmm.controller;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RestController;

/**

*@autherTerry Cheng

*@Date31/08/2017

**/

@RestController

public classIndexController {

@RequestMapping("/")

publicStringindex() {

return"Hello by Terry Cheng!";

}

}

5. 点击运行,就可以通过浏览器访问http://localhost:8080,查看运行结果了。

6. 作为企业级的项目,测试代码必不可少

packageorg.penguin.study.boot.gbmm.controller;

import staticorg.hamcrest.Matchers.equalTo;

import staticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

import staticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.http.MediaType;

importorg.springframework.test.context.junit4.SpringRunner;

importorg.springframework.test.web.servlet.MockMvc;

importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;

/**

*@autherTerry Cheng

*@Date31/08/2017

**/

@RunWith(SpringRunner.class)

@SpringBootTest

@AutoConfigureMockMvc

public classIndexControllerTest {

@Autowired

privateMockMvcmvc;

@Test

public voidgetIndex()throwsException {

mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())

.andExpect(content().string(equalTo("Hello by Terry Cheng!")));

}

}

上一篇下一篇

猜你喜欢

热点阅读