SpringBoot笔记(一) HelloWorld

之前对Spring框架有些了解,也没多用。不过看了看Spring Boot倒是感觉确实很简单,上手很容易,知道它是现在最流行的微服务架构。

特点

  1. Spring Boot和之前的Spring并不是继承关系
  2. 习惯大于配置,简化maven,自动配置spring
  3. 嵌入的Tomcat,无需部署war包
  4. 没有xml和代码生成
  5. 每个项目都是独立的spring应用

根据以上几个特点,可以分析出他其实并不是一个新的框架,实质上是一个库集合,并默认配置了几乎所有的必须配置的默认项。而且因为是比较新的东西,所以官网推荐新项目使用,因为旧项目改造的成本太大。

开始构建

他的构建相当简单

https://start.spring.io/

在官网的start页面填好信息,官网就会帮忙打包好现成的项目,编译一下就可以直接运行了。

然而这里用idea来演示,同样可以嵌入:

1

2

3

经过以上几步,现在项目框架基本就起来了

编写Hello World

接下来写个Controller作为控制器编写接口

package com.jiataoyuan.helloworld.controller;

import org.springframework.web.bind.annotation.*;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/3/20 0020
 * @description description
 */
//@RestController是默认的控制类接口
@RestController
public class HelloController {
    // @GetMapping是@RequestMapping(method = RequestMethod.GET)的缩写
    @GetMapping("/")
    public String main(){
        return "Hello World!";
    }

    @GetMapping("/hello")
    public String hello(){
        return "WelCome To Hello Page!";
    }

}

现在定义了两个接口,然后启动,现在可以访问接口

http://localhost:8080

4

http://localhost:8080/hello
5

测试类

默认的测试类什么都没写,直接启动会默认扫描所有的接口进行测试

也可以自行编写测试方法

package com.jiataoyuan.helloworld;

import com.jiataoyuan.helloworld.controller.HelloController;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


/**
 * {@link HelloController}
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWorldApplicationTests {

    @Test
    public void contextLoads() {

    }

    @Test
    public void testHello(){
        HelloController controller = new HelloController();
        Assert.assertEquals("Hello World!", controller.main());
        Assert.assertEquals("WelCome To Hello Page!", controller.hello());
    }

}

猜你喜欢

转载自blog.csdn.net/lftaoyuan/article/details/80053892