SpringBoot入门
1.第一个SpringBoot程序
2.原理初探 - 自动装配
pom.xml
- spring-boot-starter-parent:核心依赖在父工程中
- 我们在写或者引入一些SpringBoot依赖的时候,不需要指定版本
启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency
- 启动器就是SpringBoot的启动项目
- 比如spring-boot-starter-web,就会帮我们自动导入web环境的所有依赖
- SpringBoot会将所有的功能场景,都变成一个个启动器
- 使用功能就只要找到对应的启动器就可以了
start
主程序
//@SpringBootApplication 来标注一个主程序类
//说明这是一个Spring Boot应用
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
//启动了一个服务
SpringApplication.run(SpringbootApplication.class, args); }
}
@SpringBootApplication
SpringBoot所有自动配置都是在启动的时候扫描并加载:spring.factories
所有的自动配置类都在这里面,但是不一定会生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器了,有启动器,我们自动装配就会生效,配置成功
- SpringBoot在 启动的时候,从类路径下/META-INF/spring.factories 获取指定的值
- 将这些自动配置的类导入容器,自动配置就会生效
- 整合javaEE,解决方案的自动装配的东西都在 spring-boot-autoconfigure-2.4.4.jar 这包下
- 它会把所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中
- 它会给容器中导入非常多的自动配置类 (xxxAutoConfiguration) ,就是给容器中导入这个场景所需的所有组件,并配置好这些组件
SpringApplication
- 推断应用的类型是普通的项目还是Web项目
- 查找并加载所有可用初始化器 , 设置到initializers属性中
- 找出所有的应用程序监听器,设置到listeners属性中
- 推断并设置main方法的定义类,找到运行的主类
核心
- xxxxAutoConfigurartion:向容器中自动配置组件
- xxxxProperties:自动配置类,装配配置文件中自定义的一些内容
3.yaml配置注入
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的
-
application.properties
-
- 语法结构 :key=value
-
application.yml
-
- 语法结构 :key:空格 value
**配置文件的作用 :**修改SpringBoot自动配置的默认值,因为SpringBoot在底层都给我们自动配置好了;
语法要求严格
- 空格不能省略
- 以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。
- 属性和值的大小写都是十分敏感的。
# 对象
student:
name: 张三
age: 20
# 行内写法
student: {name: 张三,age: 20}
# 数组
pets:
- cat
- dog
- pig
pets: [cat.dog,pig]
yaml可以直接给实体类赋值
JSR-303校验
在实体类上加入 @Validated//数据校验
标签
可在实体类属性上添加以下标签
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=)
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则 正则表达式
数值检查
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为时无法转换为int,但可以转换为Stirng为“ ” ,Integer为null
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
4.SpringBoot Web开发
1.静态资源处理
- 在SpringBoot,我们可以使用以下方式处理静态资源
- webjars 访问
localhost:8080/webjars/
- public, static, /**, resouorces 访问
localhost:8080/
- webjars 访问
- 优先级:resources>static(默认)>public
2.首页定制
可将 index.html
放入静态资源文件夹下 直接为首页
若通过 controller 跳转则将文件放在 templates 下 在 templates 目录下的所有页面,只能通过controller 来跳转 需要模板引擎的支持 thymeleaf
3.模板引擎 - Thymeleaf
导包
<!--Thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
使用thymeleaf,只需要导入对应的依赖,我们就可以将html放入templates目录下即可
//ThymeleafProperties 源码
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
@Controller
public class HelloController {
@RequestMapping("/test")
public String hello(Model model) {
model.addAttribute("msg", "hello,springboot");
model.addAttribute("msg", "<h1>hello,springboot</h1>");
model.addAttribute("users", Arrays.asList("张三","李四"));
return "test";
}
}
<!--所有的html元素都可以被thymeleaf替换接管:th:元素名-->
<div th:text="${msg}">${msg}</div>
<div th:utext="${msg}">${msg}</div>
<hr>
<h3 th:each="user:${users}" th:text="${user}"></h3>
<h3 th:each="user:${users}">[[${user}]]</h3>
5.扩展SpringMVC
package com.ccby.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
//扩展springmvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//ViewResolver 实现了视图解析器接口的类,就可以把它看作视图解析器
@Bean
public ViewResolver myViewResolver() {
return new MyViewResolver();
}
//自定义一个自己的视图解析器
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
//官方建议
//视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//由 ccby 跳转到 test
registry.addViewController("/ccby").setViewName("test");
}
}
6.整合JDBC
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置文件 application.yml
spring:
datasource:
username: root
password: 123456abcd
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=ture&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
测试
@SpringBootTest
class Springboot04DataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//默认数据源 class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
//获取数据连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
查询
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库所有信息
//在没有实体类的情况下查询
@GetMapping("/userList")
public List<Map<String, Object>> userList() {
String sql = "select * from mybatis.user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
}
7.整合Druid
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
配置文件 application.yml
spring:
datasource:
username: root
password: 123456abcd
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=ture&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
config
package com.ccby.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//设置账户密码
HashMap<String, String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "123456");
//允许谁可以访问
initParameters.put("allow", "");
//设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
//过滤器
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParameters = new HashMap<>();
initParameters.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParameters);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
8.整合Mybatis
依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置文件 application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf-8
username: root
password: 123456abcd
# 整合mybatis
mybatis:
# 起别名
type-aliases-package: com.ccby.pojo
# 指明mapper 配置文件
mapper-locations: classpath:mybatis/mapper/*.xml
接口
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
}
mapper.xml
<?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.ccby.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from mybatis.user
</select>
</mapper>