SpringBoot基础总结

[TOC]

概述

springBoot是Spring项目中的一个子工程,与我们所熟知的Spring-framework 同属于spring的产品,使用springboot,可以让我们快速的构建庞大的spring项目(包括web 持久化),并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让我们关注业务而非配置

为什么要使用SpringBoot?

它的出现解决了传统spring项目以下的问题:

  • 配置负责繁多

​ 每一个组件集成spring都需要编写对应配置文件,比如appplicationContext-xxx.xml

  • 混乱的依赖管理

​ 在spirng中想集成对应组件时,需要导入N多的pom,并且还有考虑版本。

我们使用SpringBoot创建java应用,只需填写很少配置和依赖就能快速搭建,并使用java –jar 启动它,就能得到一个生产级别的web工程。非常方便

入门

首先创建好一个maven项目,然后在pom.xml中加入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 指定SpringBoot的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>

<!-- 导入SpringBoot的Jar包-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

然后编写一个Controller类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.ifueen.hello;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "Hello SpringBoot";
}
}

最后编写一个配置类来启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.ifueen.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* SpingBoot的引导类
*/
@SpringBootApplication
public class HelloSpringBoot {
public static void main(String[] args){
//加载这个控制器
SpringApplication.run(HelloSpringBoot.class);
}
}

启动这个配置类,然后在浏览器中输入localhost:8080/hello就可以看到效果了

项目结构

一个SpingBoot的基本项目结构如下

1
2
3
4
5
6
7
src
--main
--java
--resources
--static //静态资源目录
--templates //模板页面目录,如:jsp ,ftl
--application.properties/application.yml //默认配置文件

打包

pom.xml中导入打包插件

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

打包完成后在cmd中运行命令

java -jar xxx.jar

SpringBoot读取配置

使用@Value标签

配置文件

1
2
# 设置端口
server.port=5050

绑定配置的对象

1
2
3
//读取端口
@Value("${server.port}")
private String port;

使用@ConfigurationProperties

配置文件

1
2
3
4
5
#配置数据库
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
db.username=root
db.password=123456

新建一个类来存放读取的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.ifueen.hello.read_properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
* 读取配置文件的类
*/

@Component
@ConfigurationProperties(prefix = "db")
public class DbProperties {

private String driverClassName;
private String url;
private String username;
private String password;

@Override
public String toString() {
return "DbProperties{" +
"driverClassName='" + driverClassName + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}

public String getDriverClassName() {
return driverClassName;
}

public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

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;
}
}

多环境切换

方式一

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
profiles:
active: test #激活(选择)环境test
---
spring:
profiles: dev #指定环境名字dev
server:
port: 9999
---
spring:
profiles: test #指定环境名字test
server:
port: 8888

方式二

通过配置文件的名字来识别环境

application-dev.yml

1
2
server:
port: 9999

application-test.yml

1
2
server:
port: 8888

application.yml

1
2
3
4
spring:
profiles:
active: test
#根据文件名字配置 application-dev.properties

日志使用

基本使用

1
2
3
4
5
6
7
//日志
private static Logger log = LoggerFactory.getLogger(HelloController.class);

log.debug(connection.toString());
log.error("错误信息s");
log.warn("警告信息");
log.info("详细信息");

配置日志

1
2
3
4
5
6
# 配置日志
logging.level.root=info
logging.level.com.ifueen.hello=trace
logging.file=mylog.log
logging.pattern.console=%white(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%lsn) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{10}) - %cyan(%msg%n)
logging.pattern.file=%white(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%lsn) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{10}) - %cyan(%msg%n)

指定配置文件配置logback-spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="5 seconds" debug="false">

<!-- 定义输出日志的格式和位置 -->
<property name="SpringBoot_Log" value="%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n" />


<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${SpringBoot_Log}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>

<!--输出到文件-->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/springboot.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>logs/springboot-%d{yyyyMMdd}-%i.log.gz</fileNamePattern>
<!-- 单个文件最大值 -->
<maxFileSize>5KB</maxFileSize>
<!-- 保留历史 -->
<maxHistory>30</maxHistory>
<!-- 总文件大小 -->
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${SpringBoot_Log}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 输出级别 -->
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>


<logger name="com.ifueen" level="trace" additivity="false">
<appender-ref ref="console"/>
<appender-ref ref="file"/>
</logger>
</configuration>

SpringBoot集成Thymeleaf

导入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

创建模板 resources/templates/hello.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>欢迎奥</title>
<script src="webjars/jquery/3.4.1/jquery.js"></script>
</head>
<script>
alert($)
</script>
<body>
<h1>让我康康</h1>
<div th:text="${msg}"></div>
</body>
</html>

Controller配置

1
2
3
4
5
@RequestMapping("/hello")
public String home(Model model){
model.addAttribute("msg","我们不能失去信仰");
return "hello";
}

Thymeleaf的自动配置原理

1
2
@EnableAutoConfiguration 开启自动配置功能,通过一个AutoConfigurationImportSelector导入选择器去扫描 spring-boot-autoconfigure-2.0.5.RELEASE.jar 自动配置包下面的 spring.factories 文件中的很多很多的自动配置的类
而:ThymeleafAutoConfiguration 是的Thymeleaf的自动配置 ,在这个自动配置类里面通过一个ThymeleafProperties去读取配置文件中的配置(也有默认配置) ,来自动配置Thymeleaf,比如Thymeleaf的视图解析器的自动配置如下:
1
2
3
4
5
6
7
@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
...
return resolver;
}

静态资源

1.静态资源目录

resource/static

2.webjars

导入jquery依赖 ( http://www.webjars.org/)

1
2
3
4
5
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

导入jquery的js

1
<script src="/webjars/jquery/3.4.1/jquery.js"></script>

SpringBoot中的MVC配置

1.配置拦截器

定义拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.ifueen.hello;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 拦截器
*/
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截");
return true;
}
}

注册拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.ifueen.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* SpringMVC的配置
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginCheckInterceptor loginCheckInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截所有
registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/xx").setViewName("xx.html");
}

}
2.添加视图控制器
1
2
3
4
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/xx").setViewName("hello2.html");
}

当访问/xx 定位到 templates/hello2.html

集成DataSource(连接池)

1.导入依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!-- mysql 数据库驱动. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>

手动配置方式

手动配置四个属性

1
2
3
4
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
db.username=root
db.password=123456
1
2
3
4
5
6
@Bean
@ConfigurationProperties(prefix = "db")
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
return dataSource ;
}

自动配置方式 (重点)

1
2
3
4
5
# 配置datasource -- 自动配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

####

❤赏点钱让我买杯快乐水8❤