(一)搭建一个简单的springboot项目
一、环境依赖
(1)最低需要jdk8,不建议使用jdk10及以上版本,可能会报错。
(2)需要gradle4.0或maven3.2以上版本,本文使用maven进行管理。
(3)集成开发工具,eclipse或者是idea,idea需要付费使用,本文使用eclipse开发。
二、手工搭建一个springboot项目,输出一个helloworld
jdk安装、环境变量配置,maven安装调试在这里就不说明了
(一)创建一个maven工程
1、打开eclispse,new-》file-》other project 出现下图,找到Maven项目,选在maven project
2、勾选create a simple project
3、填写好group id 、artifact id,点击finish 就创建好一个简单的maven工程。
(二)添加springboot依赖
(1)新建项目的pom.xml文件中复制下列内容,这里我使用的springboot 2.1.0版本
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zc</groupId> <artifactId>springboot_demo</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- springboot的父级依赖,用以提供maven的相关依赖,这里选择2.1.0版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> <relativePath /> </parent> <!-- 配置运行环境 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <!-- 引入springboot的web依赖 --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
(2)依赖包下载完成后,项目可能会报错,这时只要右键项目,maven-》update project
(3)我们写一个简单的controller,输出一个helloworld,这里在controller中运行了一个main方法,使用@EnableAutoConfiguration为springboot提供给一个程序入口,正常情况下我们应该单独写一个入口类,这时要确保这个类在项目代码的根目录,以确保项目运行时能够扫描到所有的包。
/** * */ package controller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @author zc * */ @Controller @EnableAutoConfiguration public class TestController { @RequestMapping(value="/hello") @ResponseBody public String helloWorld() { return "hello world"; } public static void main(String args[]) { SpringApplication.run(TestController.class, args); } }
(4)springboot继承了tomcat,这是我们run java application,就可以通过localhost:8080/hello来输出一个hello world 页面了。
springboot在注解的集成上做的很好。比如上面的程序中我们使用了 @ResponseBody 来向页面输出数据 ,其实springboot中有 @RestController 注解,集合了@Controller 和@ResponseBody,只需要在类上注解为 @RestController 就可以了。