小工具      在线工具  汉语词典  dos游戏  css  js  c++  java

Spring Boot基础

# Spring Boot,spring boot,java,spring 额外说明

收录于:23天前

Spring Boot简介

Spring应用需要大量的配置,各种XML配置、注解配置让人眼花缭乱。为了简化Spring应用的构建和开发过程,Pivotal团队提供了一个基于Spring的新开源框架,这就是Spring Boot。

SpringBoot是基于SpringMVC构建的新一代Web开发框架。与SpringMVC相比,SpringBoot的配置更加简单。

在这里插入图片描述

pom中添加对SpringBoot的依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    <!-- ... -->
</dependencies>

Spring Boot 提供了大量开箱即用(out-of-the-box)的依赖模块,例如 spring-boot-starter-redis、spring-boot-starter-data-mongodb 和 spring-boot-starter-data-elasticsearch等。这些依赖模块为 Spring Boot 应用提供了大量的自动配置,使得 Spring Boot 应用只需要非常少量的配置甚至零配置,便可以运行起来,更多的精力专注于业务逻辑的开发。春季启动启动器
在这里插入图片描述

Spring Boot应用

创建一个新的SpringBoot应用程序:

@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
    
        SpringApplication.run(Application.class,args);
    }
}


//或者
@SpringBootApplication
public class Application {
    
    public static void main(String[] args) {
    
        SpringApplication.run(applicationClass, args);
    }

    private static Class<Application> applicationClass = Application.class;
}

MVC部分与Spring MVC一致:

@Controller
@RequestMapping("/test")
public class TestCtrl {
    
    @GetMapping("/hello")
    @ResponseBody
    public String Hello(){
    
        return "<h5>Hello Spring Boot</h5>";
    }

}

Spring Boot内置了servlet容器和Tomcat服务器,并且默认配置了Servlet。可以直接启动主任务程序:

在这里插入图片描述
在这里插入图片描述
spring boot默认的上下文是/不是项目名,直接输入接口映射访问。

SpringBoot内置了一个Tomcat服务器,它也是一个内置的Servlet容器。因此,直接运行项目就可以看到效果。不需要额外的部署或者Servlet相关的配置。同时SpringBoot也会帮我们做很多配置工作。通过@SpringBootApplication注解,它会帮助我们开启@EnableWebMvc和@ComponentScan功能,这意味着SpringBoot和SpringMvc会寻找同一个包下的@Controller、@Configuration等类进行自动配置。

Spring Boot配置文件

得益于 Spring Boot 的启动器机制,Spring Boot 无需导入各种依赖项并配置各种 XML 配置文件。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
数据库驱动所需参数,或服务参数都将在这些配置文件配配置。

YAML/YML/PROPERTIES

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
application.properties/yml/yaml是默认配置spring boot参数的,会被自动识别。

name: abc

# 对象
person:
  name: zhangsan
  age: 20

# 对象的行内写法
person1: {
    name: laowang,age: 20}

#数组
address:
  - beijing
  - shanghai

#数组行内写法
address1: [wuhan,hangzhou]

#变量
message1: 'hello \n world'  #原样输出
message2: "hello \n world"  #识别含义字符

#引用参数
description: ${
    message1}

获取配置参数

读取配置内容:
@Value注解
该注解读取配置文件定义的属性值,也可读取IoC容器的bean的属性,方法支持SpEl表达式。
Environment对象(配置文件对象)

//由于spring boot默认读取application.properties文件所以不用注解导入
@RestController
@RequestMapping("/print")
public class Test1Ctrl {
    

    @Value("${name}") private  String name;   //字符串注入
    @Value("${address[0]}") private String address;  //数组注入
    @Value("${person.name}") private String person;  //注入对象属性

    @Autowired
    private Environment environment;  //springboot默认读取的文件装配到配置文件对象

    @GetMapping("/name")
    public String printName(){
    
        return name;
    }

    @GetMapping("/list")
    protected String printList(){
    
        return address;
    }

    @GetMapping("/person")
    public String printPerson(){
    
        return person;
    }

    @GetMapping("/environment")
    public String printEnvironment(){
    
        return environment.getProperty("description");
    }

}

@ConfigurationProperties
将配置文件映射为一个配置类,在自动装配来获取值。

//Student.java:
@Component   //将该类注入到IoC容器
@ConfigurationProperties(prefix = "student")  //该注解实现了将配置文件映射为一个类,prefix绑定配置类的其中一个对象
public class Student {
    
    private String name;
    private String id;
}


//application.yaml
student:
  name: lihua
  id: s001


//controller
@RestController
@RequestMapping("/property")
public class Test2Ctrl {
    

    @Resource
    private Student student;   //注意将Student类注入IoC容器并通过@ConfigurationProperties注解将配置文件映射为一个bean

    @GetMapping("/student")
    protected Student printStudent(){
    
        return student;
    }
}

profile

开发Spring boot时,会在不同的环境中安装一组程序,例如开发环境、测试环境、生产环境。数据库地址、服务器端口等配置不同。每次打包的时候都要修改配置文件,非常麻烦。 Profile 该功能用于动态配置切换。

  • 配置文件配置方法
  1. 多profile文件方式
    在这里插入图片描述
    在这里插入图片描述
    在主配置文件中设置激活的配置文件,该文件就会生效。

  2. yml多文档模式

通过---分割不同工作区。

  • 配置文件激活方法
  1. 配置文件

上述配置文件中的active属性等于谁就启动。

  1. 虚拟机命令
    在这里插入图片描述

  2. 命令行参数

Spring boot可以打成jar包通过java -jar [jar包路径]即可运行项目,在该命令后配置启动参数文件java -jar [jar包路径] --spring.profiles.active=pro即可启动active=pro的配置。

配置文件加载顺序

在这里插入图片描述
每个配置文件都会加载,重复的优先级高的生效。除了内部配置文件的配置,也可以通过命令行实现外部文件的配置,在运行jar包时,配置响应的参数,或直接新的配置文件的位置来覆盖内部配置。

静态资源默认读取目录

在这里插入图片描述

Spring boot整合其他框架

  • 单元测试

引入starter-test依赖;在测试类上添加注解、@RunWith(SpringRunner.class)和@SpringBootTest(class=启动类.class)

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
    
    @Autowired
    private UserService userService;

    @Test
    public void addTest(){
    
        userService.userAdd();
    }
}

//别忘了将测试类注入IoC容器
@Service
public class UserService {
    
    public void userAdd(){
    
        System.out.println("add...");
    }

}

在这里插入图片描述

  • 整合Redis
    导入Redis依赖,配置redis,注入RedisTemplates模板

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <scope>test</scope>
        </dependency>
spring:
  redis:
    host: 127.0.0.1
    port: 6379
 @Autowired
    private RedisTemplate redisTemplate;

    public void redisTest(){
    
        redisTemplate.boundValuesOps("name").set("zhangsan");

        Object name=redisTemplate.boundValuesOps("name").get();
        System.out.println(name);
    }
  • 集成mybatis

引入mybatis依赖和数据库驱动;编写DataSource和myabtis的相关配置,定义所需的实体类来实现dao和mapper注解,或者开发配置文件。

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

Mybatis可以用于注解开发或者配置文件开发。方法如下:

注释开发

  1. yml数据源配置

Spring Boot的默认应用程序配置文件提供了数据源配置。如果按照规定的语法写的话,是可以被spring识别的。当然,你也可以导入druid连接池,然后配置datasource数据源。


#datasource配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/[数据名]?characterEncoding=utf-8
    password: ...
    username: ...


  1. @Mapper注解替换xml配置文件

从mybatis3.4.0开始加入了@Mapper注解,代替xml配置文件,实现完全注解开发,在普通项目中我们需要读取xml配置文件,构建SqlSessionFactory和SqlSession获取Mapper类,再调用方法。而@Mapper注解集成了这些功能,无需配置。注解在一个Mapper映射类上,就能完成SqlSessionFactory和SqlSession的创建,并调用getMapper()方法返回一个Mapper类。

在这里插入图片描述
spring也提供了@MapperScan是org.mybatis.spring的注解共差不多。
在这里插入图片描述

  1. 编写 POJO
public class User {
    
    private String username;
    private String password;

    public String getUsername() {
    
        return username;
    }

    public void setUsername(String username) {
    
        this.username = username;
    }

    public String getPassword() {
    
        return password;
    }

    public void setPassword(String password) {
    
        this.password = password;
    }

    @Override
    public String toString() {
    
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  1. 编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
    
    //数据库测试变量
    @Autowired
    private UserMapper userMapper;
    @Test
    public void selectAll(){
    
        List<User> list= userMapper.selectAll();
        System.out.println(list);
    }
}

//spring自动创建SqlSession调用getMapper()方法

在这里插入图片描述

  • mybatis for spring boot的XML配置开发

ssm项目中xml配置文件路径和mapper映射路径都是需要配置的并注入IoC容器的,spring boot由默认的配置,有的需要覆盖成自己的在指定位置覆盖生效applicationssm环境设置

  1. application文件中对mybatis的默认配置进行覆盖。(mybatis-spring-boot-starter导入时就有默认配置了)
# datasource
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8
    password: ...
    username: ...

# mybatis配置
mybatis:
  config-location:   #指定mybatis核心配置文件,用默认配置即可
  mapper-locations: classpath:mapper/*Mapper.xml   #mapper.xml映射路径
  type-aliases-package: com.example.springbootdemo.model     #配置resultType等类型的全限定名,然后resultType=类名即可

映射路径需要覆盖默认配置。

  1. 编写mapper.xml配置文件和map映射器类
<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springbootdemo.dao.UserMapper">
<select id="selectAll" resultType="com.example.springbootdemo.model.User">
<!-- type-aliases-package进行了配置这里可以直接写User-->
    select * from user
</select>
</mapper>

如果没配置type-aliases-package又没写全就会出现这样的错误:
在这里插入图片描述

@Repository
@Mapper
public interface UserMapper {
    
    //@Select("select * from user")
    List<User> selectAll();
}
  1. POJO与上面的User相同,测试类如下
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootDemoApplication.class)
public class UserTest {
    
 
    //数据库测试变量
    @Autowired
    private UserMapper userMapper;

    @Test
    public void selectAll(){
    
        List<User> list= userMapper.selectAll();
        System.out.println(list);
    }

在这里插入图片描述
由此可以看出,注解开发比配置文件开发更简单,少了一个@Select,@Insert…的注解,却多了mybatis的覆盖配置参数,mapper.xml文件,mapper接口,其他都一样。除了很难的sql语句建议注解开发。

Spring Boot自动配置

Spring Boot的最大的特点就是简化了各种xml配置内容,省去了SSM框架各种xml配置,如:数据源、连接池、会话工厂、事务管理等。spring实现完全注解开发,Spring Boot就是全用注解来对一些常规的配置做默认配置,简化xml配置内容,使你的项目能够快速运行。

感谢作者@木竹子
感谢作者@
感谢作者@Java3y
感谢以上作者虽然我还看不懂 -。

@Enable*注解
Spring Boot注解提供了提供了很多该注解盖头的注解,用于开启某些功能,底层时使用@Import注解到日一些配置类,实现bean的动态加载。

@Enable注解导入的依赖于@Import注解的类会被spring、@Enable加载到IoC容器中注解导入@Import注解。

@EnableAutoConfiguration注解

该注解内部使用@Inport(AutoConfiggurationImportSelector.class)来加载类。
配置问津位置:META-INF/spring.factories,该注解定义了大量配置类,当spring启动时,会加载这些配置类,初始化bean。

Spring Boot切换内置web服务器

spring boot的web环境默认使用Tomcat服务器,但Spring boot内置了四种服务器可供选择:jetty,
netty,tomcat,undertow

<!--将tomcat排除-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   		<artifactId>spring-boot-starter-web</artifactId>
		<executions>
			<exclusions>
				<artifactId>spring-boot-starter-tomcat</artifactId>
				<groupId>org.springframework.boot</groupId>
			</exclusions>
		</executions>
<dependency>
<!--引入新的服务器依赖-->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <scope>test</scope>
        </dependency>

Spring Boot事件监听

spring监听机制是对java提供的监听机制的封装。 java事件的监听机制有以下几类:

  • Event:继承java.util.EventObject类的对象
  • 事件源Source:任意Object对象
  • Listener监听器:实现java.util.EventListenter接口的对象

春季启动监听器:

  • 应用程序上下文初始化器
  • SpringApplicationRunListener
    在这里插入图片描述

从上到下依次是:项目启动中,环境开始准备,环境准备完毕,上下文开始加载,上下文加载完成,项目启动完成,项目启动失败的项目声明周期函数

上面要生效需要配置,再spring boot项目中的resources目录下创建MATA-INF/spring.factores并配置:

org.springframework.contex.ApplicationContextInitializer=exanple.text.listenerMyApplicationContextInitializer


//前面是监听器,后面是自定义的实现类
//注意都要写全限定名

//SpringApplicationRunListener的配置一样,再实现类重写方法实现监听

//SpringApplicationRunListener需要重写有参构造方法,参数为事件源和agrs的String数组
  • CommandLineRunner
    接口偶一个run方法,当项目启动后执行run方法。
  • ApplicationRunner
    接口偶一个run方法,当项目启动后执行run方法。

Spring Boot监控

Spring Boot自带监控功能,可以监控程序内部运行状态,如bean加载状态、配置属性、日志信息等。

  1. 导入相关坐标
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <scope>test</scope>
        </dependency>
  1. 启动程序并访问http://localhost:8080/actuator

模板引擎

在java领域,表现层技术主要有四种:jspfreemarkervelocityThymeleaf

对于传统jsp或者其他模板来说,没有一个模板引擎的后缀为.html,就拿jsp来说jsp的后缀为.jsp,它的本质就是在一个html文件java语法、标签然后执行时候通过后台的jre重新编译这个文件最终返回一个html页面,离不开服务端,浏览器端是无法直接识别.jsp文件。

执行过程中依赖于服务端的jre
在这里插入图片描述
JSP模板引擎

自由标记

Spring Boot项目部署

spring boot项目支持两种部署到服务器的方式

  1. jar包

用IDE打成jar包,再上传到服务器,再同一目录下java -jar [jar包]

  1. 战争包

在pom中修改打包方式<packaging>war</packaging>,主程序继承SpringBootServletInitializer并重写一个方法:

@SpringBootApplication
public class SpringbootupdateApplication extends SpringBootServletInitializer {
    

    public static void main(String[] args) {
    
        SpringApplication.run(SpringbootupdateApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    
        return builder.sources(SpringbootupdateApplication.class);
    }
}

可以在<build>标签中用指定打包名称:


    <build>
        <finalName>${filename}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

打包后,直接将war文件放入tomcat中即可,上下文连接就成为war包的名称。

. . .

相关推荐

额外说明

算法题解_哥德巴赫曾经猜想

本周总结 文章目录 本周总结 一、哥德巴赫曾猜测 1.思路 2.代码 一、哥德巴赫曾猜测 题目描述 德国数学家哥德巴赫曾猜测:任何大于6的偶数都可以分解成两个素数(素数对)的和。但有些偶数可以分解成多种素数对的和,如: 10=3+7,10=5+5,即10

额外说明

一篇文章看懂字符集! (详细解释utf8、utf8mb3和utf8mb4的区别,以及utf8mb4_unicode_ci和utf8mb4_general_ci的区别)

目录 前言 一、浅谈字符集 二、 数据库与字符集 1) 数据库utf8 、utf8mb3和 utf8mb4的区别 如何选择? 2)数据库的排序规则和性能 ① 什么是排序规则 ② utf8mb4_unicode_ci 和 utf8mb4_general_c

额外说明

REDIS6_分布式存储终极性能目录

Juc24_AQS的概述、体系架构、深入源码解读(非公平)、源码总结 鸟欲高飞先振翅,人求上进需读书! 部分高级暂不公开 GUAVA本地缓存_概述、优缺点、创建方式、回收机制、监听器、统计、异步锁定 REDIS01_概述、安装、key、字符串String

额外说明

2023 最新版navicat 下载与安装 步骤及演示 (图示版)

2023 最新版navicat 下载与安装 步骤演示 -图示版 1. 下载Navicat 2 .安装navicat 160 博主 默语带您 Go to New World. ✍ 个人主页—— 默语 的博客-- 《java 面试题大全》 -惟余辈才疏学浅,

额外说明

dockerfile构建镜像

dockerfile是什么 一套构建docker镜像的脚本语言,就像每种开发语言都有自己的编写规范一样,dockerfile也是如此,通过编写dockerfile文件,然后通过build,即可按照dockerfile的要求达到构建一个目标期望的镜像的目的

额外说明

【Java编程案例】用户管理系统实现

用户管理是许多应用程序中的核心功能之一。本文将介绍如何使用Java编写一个简单的用户管理系统,实现用户的注册、登录、昵称修改和注销等功能。 在本文中,我们将使用Java编写一个名为User的类来实现用户管理系统。该类包含用户的注册、登录、昵称修改和注销等

额外说明

Java二叉树

Java二叉树 -1. 树型结构(了解)- -1.1 概念- -1.2 概念(重要)- -1.3 树的表示形式(了解)- -1.4 树的应用- -2. 二叉树(重点) - -2.1 概念- -2.2 二叉树的基本形态- -2.3 两种特殊的二叉树- ❤️

额外说明

水仙花数(Java实现)

 春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的: “水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。 import java.

额外说明

MNIST数据集手写数字识别(一)

        MNIST数据集是初步学习神经网络的很好的数据集,也是拿来教学,不可多得的好教材,有很多知识点在里面。官网下载地址,可以自己手动下载,当然也可以通过下面的代码自动下载【urllib.request(3.x版本以上)】,下载下来的是四个gz

额外说明

【FinalShell】win10 / win 11:远程连接 Linux 工具 FinalShell 下载、安装

目录 一、前言 二、FinalShell 下载 (1)Windows 版下载(示例) (2)macOS 版下载 (3)Linux 版下载 三、FinalShell 安装 一、前言 xshell 和 xftp 是较为常用,Windows 远程连接 Linu

ads via 小工具