JEE Study|JAVA EE|企业级开发学习网

标题: Spring-Boot进阶:1 - 入门 [打印本页]

作者: JeeStudy    时间: 2017-5-4 15:36
标题: Spring-Boot进阶:1 - 入门
1.下载官方推荐的Spring Tool Suite (STS)IDE  直接下载(3.8.4_x64)
2.解压 下载 后的zip文件 spring-tool-suite-3.8.4.RELEASE-e4.6.3-win32-x86_64.zip
[attach]196[/attach]
3.启动
[attach]197[/attach]
4.新建Spring Boot 项目
a.File → New → Spring Starter Project
[attach]198[/attach]
b.配置基本工程信息
[attach]199[/attach]
c.选择Web工程
[attach]200[/attach]
d.从官方提供的url为模板生成工程
[attach]201[/attach]
5.Spring Boot 工程 创建完成
[attach]202[/attach]



到此一个空的Spring Boot 工程创建完成。
初体验:


写个简单的类体验一下 HelloController.java
[Java] 纯文本查看 复制代码
package com.jeestudy;

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

@RestController
public class HelloController {
        @RequestMapping("hello")
        public String hello(String name) {
                return "hello-" + name;
        }
}


运行:Application.java
Run As → Java Application
[attach]203[/attach]

启动 控制台
[attach]204[/attach]
浏览器访问:http://localhost:8080/hello?name=spring-boot
[attach]205[/attach]
测试成功!

单元测试:
[attach]206[/attach]
[Java] 纯文本查看 复制代码
package com.jeestudy;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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 org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
        @Test
        public void contextLoads() {
        }

        private MockMvc mvc;

        @Before
        public void setUp() throws Exception {
                mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
        }

        @Test
        public void getHello() throws Exception {
                mvc.perform(MockMvcRequestBuilders.get("/hello?name=spring-boot").accept(MediaType.APPLICATION_JSON))
                                .andExpect(status().isOk()).andExpect(content().string(equalTo("hello-spring-boot")));
        }
}






欢迎光临 JEE Study|JAVA EE|企业级开发学习网 (http://www.jeestudy.com/) Powered by Discuz! X3.2