体验Spring boot 零配置开发微服务
2018年12月29日星期六
体验spring boot 零配置开发微服务
1.为什么要用spring boot?
1.1 简单方便、配置少、整合了大多数框架
1.2 适用于微服务搭建,搭建的微服务与spring clound进行完美融合,因为都是spring家族
2. spring boot开发过程
2.1 启动idea
2.2 创建maven项目
2.3 引入核心: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.3,2.4,没有其它配置,就可以启动restful服务。所以证实了spring boot基本零配置来开发微服务。