Spring Boot 优点
- 快速构建独立运行的spring项目;
- 无须依赖外部Servelt容器,应用无需打成WAR包,项目可以打成JAR包独自运行;
- 提供一系列starter pom 来简化Mavende 依赖加载;
- 大量的自动配置,对主流框架的无配置继承;
- 无须配置XML,开箱即用,简化开发,同时也可以修改默认值来满足特定的需求;
- Spring Boot并不是对Spring功能上的增强,而是提供了一种快速使用Spring的方式;
- 极大地提高了开发部署效率;
环境要求
- jdk1.8(Spring Boot 推荐使用jdk1.8及以上)
- Maven 3.x(maven 3.2以上版本)
- Intellij IDEA
- Spring Boot 使用当前最新最稳定版本
开始入坑
修改Maven配置文件
- 在Maven安装目录下的settings.xml配置文件,添加配置
<!--开始处更改下载依赖的存放路径, 以下目录需要已经创建-->
<localRepository>D:\Spring Boot\maven-repository </localRepository>
<!--在mirrors标签下 添加阿里云maven私服库-->
<mirrors>
<mirror>
<id>alimaven</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>
</mirrors>
<!--在profiles 标签下指定jdk版本-->
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
IntelliJ IDEA 设置
- 在IDEA上将maven环境添加进来
快速构建 Spring Boot 项目
- 需求:浏览器发送 /hello 请求,服务器接收并处理,响应Hello World 字符串
- 分析:构建Spring Boot 项目,事实上就是创建一个Maven项目
项目创建
- 在IDEA 上创建一个空的jar类型的Maven工程
、
修改pom.xml
- 在pm.xml 中添加Spring Boot相关的父级依赖,spring-boot-starter-parent 睡一个特殊的starer,他提供了项目相关的默认依赖,使用它之后,常用的包依赖可以省去version 标签。
- 在dependencies添加构建Web项目相关的依赖
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 修改完后点击右下角 Import Changes 导入相关依赖
遇坑一次
- 由于不细心 在 Maven 的 Setting.xml 配置文件中添加配置时少打了一个">";导致pom.xml文件全程爆红 和导入不进去依赖
创建控制器Controller
package com.ljp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "hello word!!";
}
}
创建一个引导类
- 作用是作为Spring Boot 项目的入口
package com.ljp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloMailAppliaction<spring> {
public static void main(String[] args) {
SpringApplication.run(HelloMailAppliaction.class,args);
}
}
- 在浏览器输入locallhost:8080/hello
至此 第一个Spring Boot 项目创建完毕
(本文根据梦学谷教程学习所得)