Spring boot 零配置开发微服务

20181229日星期六

体验Spring boot 零配置开发微服务

1.为什么要用Spring  boot

   1.1 简单方便、配置少、整合了大多数框架

   1.2 适用于微服务搭建,搭建的微服务与Spring clound进行完美融合,因为都是Spring家族

2. Spring boot开发过程

2.1 启动Idea

2.2 创建Maven项目

2.3 引入spring-boot-starter-web核心:Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container

2.4 引入spring-boot-starter-test核心:Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito

2.5 具体依赖如下:

2.6 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.0.4.RELEASE</version>
    <scope>test</scope>
</dependency>

2.7 创建Spring boot启动主程序:package com.wuji.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com.wuji.controller"})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

2.8 编写HelloController:

package com.wuji.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {
    @RequestMapping("/hello")
    public String index(){
        return "Hello";
    }
}

2.9 运行http://localhost:8080/api/hello

2.10 第一次写Spring boot程序运行一般会出现:whitelabel error page 这个错误,是因为默认没有加载控制器包。要在主程序加上@ComponentScan(basePackages = {"com.wuji.controller"})注解

2.11 总结:整个程序只引用了两个核心包2.32.4,没有其它配置,就可以启动Restful服务。所以证实了Spring boot基本零配置来开发微服务。

原文地址:https://www.cnblogs.com/javajiuyangzhenjing/p/10195326.html