快速上手Spring Boot应用
Spring Boot
文章目录
- Spring Boot
- 1. 概述
- 1.1 由来
- 1.2 特征
- 2. 入门程序
- 2.1 通过maven工程方式创建
- 2.2 直接通过IDEA创建
- 3. SpringBoot配置
- 3.1 概述
- 3.2 Spring Boot的配置文件
- 3.2.1 yml格式配置文件
- 3.2.2 多配置切换
- 3.3 Spring Boot属性注入
- 3.3.1 @Value注入
- 3.3.2 @ConfigurationProperties注入
- 4. Spring Boot整合SpringMVC
- 4.1 整合JSP
- 4.2 整合SpringMVC拦截器
- 5. Spring Boot整合JDBC
- 6. Spring Boot整合MyBatis
- 7. Spring Boot整合Redis
- 8. Spring Boot项目部署
1. 概述
1.1 由来
SpringBoot是由Pivotal团队在2013年开始研发、2014年4月发布第一个版本的全新开源的轻量级框架。它基于Spring4.0设计,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程。另外SpringBoot通过集成大量的框架使得依赖包的版本冲突,以及引用的不稳定性等问题得到了很好的解决
1.2 特征
- 可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs
- 内嵌Tomcat或Jetty等Servlet容器
- 提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置
- 尽可能自动配置Spring容器
- 完全不需要代码生成,也不需要XML配置
2. 入门程序
在开始之前,打开终端运行以下命令以确保安装了有效版本的Java和Maven:
$ java -version
java version "11.0.15.1" 2022-04-22 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.15.1+2-LTS-10)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.15.1+2-LTS-10, mixed mode)
$ mvn -v
Apache Maven 3.9.8 (36645f6c9b5079805ea5009217e36f2cffd34256)
Maven home: D:\software\Java\apache-maven-3.9.8
Java version: 11.0.15.1, vendor: Oracle Corporation, runtime: D:\software\Java\jdk-11
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 11", version: "10.0", arch: "amd64", family: "windows"
2.1 通过maven工程方式创建
创建一个空的Maven项目
配置pom.xml文件:
<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>edu.com</groupId>
<artifactId>SpringBootDemo01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootDemo01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
</parent>
<dependencies>
<!-- 引入web开发相关的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
创建Application.java类作为该SpringBoot项目的启动类:
package io.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 该类作为整个SpringBoot项目的启动类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
右键运行该类:
创建一个controller作为测试:
package io.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@GetMapping("hello")
@ResponseBody // 将返回的对象变为json格式
public String hello() {
return "Hello Spring Boot!";
}
}
右键启动Application.java,并在浏览器输入默认访问路径:
2.2 直接通过IDEA创建
可能使用的JDK版本为11,但是Java选项里面没有11的选项,在点击NEXT的时候报错:
Selected version of Java 17 is not supported by the project SDK '11'. Either choose a lower version
解决方法:将最上方Server URL的网址更改为阿里云下载地址:https://start.aliyun.com/。Java选项即出现11和8
目前学习阶段,先选择这两个,已经右上方对应的Spring Boot的版本,其他根据后续需要进行添加
创建HelloController.java作为测试:
package edu.com.springbootdemo02.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // @Controller + @ResponseBody
public class HelloController {
@GetMapping("hello")
public String hello() {
return "Hello Spring Boot!";
}
}
右键启动SpringBootDemo02Application.java(在构建SpringBoot项目是自动生成的项目启动类),并在浏览器输入默认访问路径即可完成测试
3. SpringBoot配置
3.1 概述
早期我们在使用Spring和SpringMVC的时候,采用的xml+注解的方式的来配置,随着后期配置的增多,xml文件的也不断地增加,而SpringBoot倡导用注解和java程序来替代xml配置文件,下面以数据库的配置让感受下SpringBoot如何简化我们的配置
3.2 Spring Boot的配置文件
Spring Boot的核心配置文件application.properties(application.yml),推荐使用yml格式文件,层级结构展示配置更加清晰
3.2.1 yml格式配置文件
YAML
是专注于写配置文件的语言,只不过是更加聚焦于数据的标记语言
YAML的基本语法规则:
1.大小写敏感
2.使用缩进表示层级关系
缩进时绝对不允许使用Tab键,只允许使用空格键
缩进的空格数不重要,只要元素左侧能对齐就可以
3.键: 值 键和值之间至少有一个空格
server:
port: 8081 # 配置服务器端口号
servlet:
context-path: /springbootdemo02 # 配置访问的根路径
3.2.2 多配置切换
application.yml
spring:
profiles:
active: dev # 切换配置
application-dev.yml
server:
port: 8082
application-pro.yml
server:
port: 8083
多配置切换的文件命名一定要规范:application-XXX.yml
3.3 Spring Boot属性注入
3.3.1 @Value注入
@Configuration
:声明一个类作为配置类,代替xml文件
@Value
:属性注入
@PropertySource
:指定外部属性文件
config/student.properties
student.name=satellite
student.age=25
Student.java
@Component
@PropertySource(value = "classpath:config/student.properties")
public class Student {
@Value("${student.name}")
private String name;
@Value("${student.age}")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
HelloController.java
@RestController // @Controller + @ResponseBody
public class HelloController {
@Autowired
Student student;
@Autowired
Phone phone;
@GetMapping("hello")
public String hello() {
return "Hello Spring Boot!";
}
@GetMapping("stu")
public Student student() {
return student;
}
@GetMapping("phone")
public Phone phone() {
return phone;
}
}
3.3.2 @ConfigurationProperties注入
Spring Boot默认加载applicaiton.properties(yml)下的属性
# 自定义配置
phone:
brand: HuaWei
price: 3999
Phone.java
@Component
@ConfigurationProperties(prefix = "phone") // 在配置文件中,以phone开头的属性都会被注入到这个类中
public class Phone {
// @Value("${phone.brand}")
private String brand;
// @Value("${phone.price}")
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
HelloController.java
@RestController // @Controller + @ResponseBody
public class HelloController {
@Autowired
Student student;
@Autowired
Phone phone;
@GetMapping("hello")
public String hello() {
return "Hello Spring Boot!";
}
@GetMapping("stu")
public Student student() {
return student;
}
@GetMapping("phone")
public Phone phone() {
return phone;
}
}
4. Spring Boot整合SpringMVC
4.1 整合JSP
1.新建一个Spring Boot工程
2.引入JSP相关依赖
<!-- 渲染JSP相关依赖 -->
<!--JavaServer Pages Standard Tag Library,JSP标准标签库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--内置tomcat对Jsp支持的依赖,用于编译Jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
3.新建src/main/webapp/WEB-INF目录
4.修改application.yml文件
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
注意:prefix路径里面的/,千万不能少
5.新建User.java
package edu.com.springbootspringmvc.model;
public class User {
private String name;
private String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
6.新建UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@PostMapping("/save")
public String saveUser(String name, String password, Model model) {
User user = new User(name, password);
model.addAttribute("user", user);
return "index";
}
}
7.修改index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>主页</title>
</head>
<body>
${user.name} --> ${user.password}
</body>
</html>
8.测试
(1)可以在项目根目录底下创建一个testHttp.http文件
POST http://localhost:8080/user/save
Content-Type: application/x-www-form-urlencoded
name=satellite&password=123456
###
(2)也可以使用postman工具来进行测试
4.2 整合SpringMVC拦截器
1.定义拦截器
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("....preHandle01....");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("....postHandle01....");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("....afterCompletion01....");
}
}
2.注册拦截器
/**
* 注册拦截器
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
3.同4.1的第8步一样进行测试
5. Spring Boot整合JDBC
1.新建Spring Boot工程,勾选Spring Boot DevTools、Spring Data JDBC、MySQL Driver
2.引入依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.com</groupId>
<artifactId>springboot-data</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-data</name>
<description>springboot-data</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入阿里巴巴druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- 自启动Druid管理后台 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>edu.com.springbootdata.SpringbootDataApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3.修改application.yml配置文件
# 连接池的配置
spring:
datasource:
druid:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
initial-size: 20
max-active: 20
min-idle: 1
4.测试
@SpringBootTest
class SpringBootJDBCTest {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
public void testSave() {
jdbcTemplate.update("INSERT INTO springboot.user(name, password) VALUES (?, ?)", "satellite", "123456");
}
}
6. Spring Boot整合MyBatis
逆向生成的文件中,存在数据库中的字段名和逆向工程生成的类的属性名不一致的问题
需要在数据库连接信息中添加以下代码
<property name="nullCatalogMeansCurrent" value="true"/>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot?useSSL=false&characterEncoding=UTF-8"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
1.添加依赖
<!-- 整合MyBatis相关的依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- 逆向生成的插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
</plugin>
2.逆向生成
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3" defaultModelType="flat">
<!--防止生成重复代码-->
<!-- <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/> -->
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot?useSSL=false&characterEncoding=UTF-8"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="edu.com.springbootdata.po"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="edu.com.springbootdata.mapper"
targetProject=".\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="edu.com.springbootdata.mapper"
targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="user" schema="springboot"/>
</context>
</generatorConfiguration>
3.修改application.yml
# mybatis配置
mybatis:
type-aliases-package: edu.com.springbootdata.po # 别名配置
mapper-locations: classpath:edu/com/springbootdata/mapper/*.xml # mapper文件路径
# mybatis输出执行的sql
logging:
level:
edu:
com:
springbootdata:
mapper: debug
4.测试
@SpringBootTest
class UserMapperTest {
@Autowired
UserMapper userMapper;
@Test
public void testSave() {
userMapper.insert(new User("chaoshihan", "2426"));
}
@Test
public void testSelect() {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andNameEqualTo("chaoshihan");
userMapper.selectByExample(userExample)
.forEach(user -> System.out.println(user.getName() + " " + user.getPassword()));
}
}
7. Spring Boot整合Redis
1.引入依赖
<!-- 整合MyBatis相关的依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
2.修改application.yml
# 配置redis连接信息
redis:
database: 1
host: 192.168.170.140
port: 6379
password: 123456
jedis:
pool:
max-wait: 5000
3.引入工具类
package edu.com.springbootdata.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类,为了方便操作redis
*/
@Component
public class RedisUtils {
@Autowired
RedisTemplate<Object,Object> redisTemplate;
/**
* 向redis中存入string类型数据
* @param key
* @param value
* @return
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key,value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据key取出redis中的string类型数据
* @param key
* @return
*/
public Object get(String key) {
return StringUtils.isEmpty(key)? null : redisTemplate.opsForValue().get(key);
}
/**
* 向redis中存入hash类型数据
* @param field
* @param key
* @param value
* @return
*/
public boolean hset(String key,Object field, Object value) {
try {
redisTemplate.opsForHash().put(key,field,value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据key和field取出redis中的hash类型的数据
* @param key
* @param field
* @return
*/
public Object get(String key, Object field) {
return StringUtils.isEmpty(key)? null : redisTemplate.opsForHash().get(key,field);
}
/**
* 通用方法:根据key删除对应的数据
* @param key
*/
public void del(String key) {
redisTemplate.delete(key);
}
/**
* 通用方法:判断key是否存在
* @param key
* @return
*/
public boolean exist(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 为某个key设置过期时间
* @param key
* @param timeout
* @return
*/
public boolean expire(String key, long timeout) {
try {
return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 查看key的剩余存活时间
* @param key
* @return
*/
public long ttl(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
}
4.测试
package edu.com.springbootdata.utils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class RedisUtilsTest {
@Autowired
RedisUtils redisUtils;
@Test
public void testSet() {
redisUtils.set("name", "satellite");
}
@Test
public void testGet() {
System.out.println(redisUtils.get("name"));
}
}
8. Spring Boot项目部署
1.将Spring Boot项目直接打包成jar包
这里可能会出现一个问题,在pom.xml文件配置下,maven打包时没有配置主类,然后在这种情况下去部署jar包则会报错:SpringBootDemo02-0.0.1-SNAPSHOT.jar r中没有主清单属性
在我的项目中,解决这个问题需要将pom.xml文件下的<skip>true</skip>
注释掉,再进行打包就可以了
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>edu.com.springbootdemo02.SpringBootDemo02Application</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
2.将jar包部署到CentOS 7下
将jar包上传到配置了JDK环境的CentOS 7下直接利用命令
java -jar ~/SpringBootDemo02-0.0.1-SNAPSHOT.jar
3.测试
在浏览器访问链接 服务器ip地址:配置的端口号
进行测试即可,例如在浏览器输入:192.168.134.140:8080