SpringBoot复习(上)

(二) yaml注入

一。 yaml语法学习

1.配置文件
  • application.properties
    • 语法结构:key= value
  • application.yml
    • 语法结构: key:空格 value
2.yaml概述
3.yaml基础语法

语法要求严格

1.空格不可省略

2.缩进表示层级关系,只要左边对齐就是同一层级的

3.属性和值大小写都是很敏感的

1):字面量

k: v

2)对象键值对

#对象,Map格式
k:
 v1:
 v2:

3)数组:(List.Set)

pets:
  - cat
  - dog
  - pig

二。注入配置文件

一.yaml注入配置文件
1.yaml注入配置文件
1.在SpringBoot项目的resources目录下新建一个文件application.yml
2.编写实体类Dog
@Component  //注册bean到容器中
public class Dog {
    private String name;
    private Integer age;
    //有参无参构造、get、set方法、toString()方法  
}
3.我们原来是用@Component和@Value注解给狗狗测试的
@Component //注册bean
public class Dog {
    @Value("阿黄")
    private String name;
    @Value("18")
    private Integer age;
}
4.在SpringBoot测试类 输出一下
@SpringBootTest
class DemoApplicationTests {
    @Autowired //将狗狗自动注入进来
    Dog dog;
    @Test
    public void contextLoads() {
        System.out.println(dog); //打印看下狗狗对象
    }
}

注入成功

img

5.我们编写一个复杂的实体类:Person类
/*
@ConfigurationProperties作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;
告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应
*/
@Component //注册bean
public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
    //有参无参构造、get、set方法、toString()方法  
}
6.yaml配置进行注入
person:
  name: qinjiang
  age: 3
  happy: false
  birth: 2000/01/01
  maps: {k1: v1,k2: v2}
  lists:
   - code
   - girl
   - music
  dog:
    name: 旺财
    age: 1
7.配置写好 然后注入到我们的类
8.IDEA 提示

springboot配置注解处理器没有找到,让我们看文档,我们可以查看文档,找到一个依赖!

img

<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>
9.一切都OK我们就去测试类测试
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    Person person; //将person自动注入进来
    @Test
    public void contextLoads() {
        System.out.println(person); //打印person信息
    }
}
2.加载指定的配置文件

@PropertySource:加载指定的配置文件

@ConfigurationProperties:默认从全局配置文件中获取值

1、我们去在resources目录下新建一个person.properties文件

name=kuangshen

2、然后在我们的代码中指定加载person.properties文件

@PropertySource(value = "classpath:person.properties")
@Component //注册bean
public class Person {
    @Value("${name}")
    private String name;
    ......  
}

3、再次输出测试一下:指定配置文件绑定成功!

img

3.配置占位符
person:
    name: qinjiang${random.uuid} # 随机uuid
    age: ${random.int}  # 随机int
    happy: false
    birth: 2000/01/01
    maps: {k1: v1,k2: v2}
    lists:
      - code
      - girl
      - music
    dog:
      name: ${person.hello:other}_旺财
      age: 1

(三 ) JSR303数据校验以及多环境切换

1.先看看如何使用
@Component //注册bean
@ConfigurationProperties(prefix = "person")
@Validated  //数据校验
public class Person {
    @Email(message="邮箱格式错误") //name必须是邮箱格式
    private String name;
}

运行结果:default message[不是一个合法的电子邮件]

2.常见参数
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
 
空检查
@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=) string is between min and max included.
 
日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则
 
.......等等
除此以外,我们还可以自定义一些数据校验规则

注意:如果yml和properties同时都配置了端口,并且没有激活其他环境 , 默认会使用properties配置文件的!

(四) 自动配置原理

一 自动装配原理
1.分析自动装配原理:

我们以HttpEncodingAutoConfiguration(Http编码自动配置) 为例解释自动装配原理

//表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件;
@Configuration 
 
//启动指定类的ConfigurationProperties功能;
  //进入这个HttpProperties查看,将配置文件中对应的值和HttpProperties绑定起来;
  //并把HttpProperties加入到ioc容器中
@EnableConfigurationProperties({HttpProperties.class}) 
 
//Spring底层@Conditional注解
  //根据不同的条件判断,如果满足指定的条件,整个配置类里面的配置就会生效;
  //这里的意思就是判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
 
//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnClass({CharacterEncodingFilter.class})
 
//判断配置文件中是否存在某个配置:spring.http.encoding.enabled;
  //如果不存在,判断也是成立的
  //即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
    //他已经和SpringBoot的配置文件映射了
    private final Encoding properties;
    //只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }
    //给容器中添加一个组件,这个组件的某些值需要从properties中获取
    @Bean
    @ConditionalOnMissingBean //判断容器没有这个组件?
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
  filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
  filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }
    //。。。。。。。
}

一句话总结:根据当前不同的条件判断,决定这个配置类是否生效

  • 一旦这个配置类生效,这个配置类就会给容器中添加各种组件
  • 这些组件的属性是从对应的properties类中获取的,这个鞋类里面的每一个属性有事和配置文件绑定的
  • 所有在配置文件中配置的属性都是在xxxxProperties中封装着
  • 配置文件能配置什么就可以参照某个功能对应的属性类
//从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(prefix = "spring.http") 
public class HttpProperties {
    // .....
}

我们去配置文件中显然可以看到

img

这就是自动装配的原理

2.精髓

1、SpringBoot启动会加载大量的自动配置类

2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;

3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)

4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可;

xxxxAutoConfiguration:自动配置类: 给容器中添加组件

xxxProperties: 封装配置文件中的相关属性

3. 了解: @Conditional

关注细节:自动配置类必须在一定条件下生效

@Conditional派生注解

作用: 必须是@Conditional指定的条件成立,才给容器中添加组件

img

我们可以通过debug=true来控制哪些属性生效

#开启springboot的调试类
debug=true

Positive matches:(自动配置类启用的:正匹配)

Negative matches:(没有启动,没有匹配成功的自动配置类:负匹配)

Unconditional classes: (没有条件的类)

(五) 自定义Starter

一 自定义Starter

1.在IDEA中新建一个空项目 spring-boot-starter-diy

2.创建Maven工程

3.在Maven工程里面创建一个SpringBoot的子项目

4.apply

5.starter中导入autoconfigure依赖

6.autoconfigure里面的pom文件都删掉,只留下一个starter

7、我们编写一个自己的服务

package com.kuang;
 
public class HelloService {
 
    HelloProperties helloProperties;
 
    public HelloProperties getHelloProperties() {
        return helloProperties;
    }
 
    public void setHelloProperties(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
 
    public String sayHello(String name){
        return helloProperties.getPrefix() + name + helloProperties.getSuffix();
    }
 
}

8.编写HelloProperties 配置类

package com.kuang;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
 
// 前缀 kuang.hello
@ConfigurationProperties(prefix = "kuang.hello")
public class HelloProperties {
 
    private String prefix;
    private String suffix;
 
    public String getPrefix() {
        return prefix;
    }
 
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
 
    public String getSuffix() {
        return suffix;
    }
 
    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

9.编写我们的自动配置类并注入bean,测试!

package com.kuang;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ConditionalOnWebApplication //web应用生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
 
    @Autowired
    HelloProperties helloProperties;
 
    @Bean
    public HelloService helloService(){
        HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;
    }
 
}

10.在resources编写一个自己的META-INF\spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.kuang.HelloServiceAutoConfiguration

3.新建项目测试我们自己写的启动器

1、新建一个SpringBoot 项目

2、导入我们自己写的启动器

<dependency>
    <groupId>com.kuang</groupId>
    <artifactId>kuang-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

3、编写一个 HelloController 进行测试我们自己的写的接口!

package com.kuang.controller;
@RestController
public class HelloController {
    @Autowired
    HelloService helloService;
    @RequestMapping("/hello")
    public String hello(){
        return helloService.sayHello("zxc");
    }
}

4、编写配置文件 application.properties

kuang.hello.prefix="ppp"
kuang.hello.suffix="sss"

5、启动项目进行测试,结果成功 !

(六) 整合JDBC

一 SpringData简介

二 整合JDBC

1.创建JDBC测试数据源
1.创建SQL模块的SpringBoot项目

img

2.配置SQL的pom文件
<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>
3.yaml连接数据库
spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
4.配置完这些配置我们就可以使用了
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
 
    //DI注入数据源
    @Autowired
    DataSource dataSource;
    @Test
    public void contextLoads() throws SQLException {
        //看一下默认数据源
        System.out.println(dataSource.getClass());
        //获得连接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        //关闭连接
        connection.close();
    }
}

HikariDataSource号称Java WEB当前速度最快的数据源,相比于传统的C3P0,DBCP. Tomcat JDBC等连接池更加优秀

2.JDBCTemplate

1.拿到了HakariDataSource 就可以拿到ava.sql.Connection,有了连接,就可以使用原生JDBC操作数据库

2.即使不使用Mybatis,Spring也提供了对JDBC做轻量级的封装: JDBCTemplate

3.CRUD方法都在JDBCTemplate中

4.SpringBoot提供了数据源而且配置好了JdbcTemplate放在容器中,程序员只需自己注入即可使用

5.JdbcTemplate的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的 JdbcTemplateConfiguration 类

JDBCTemplate提供如下方法

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

3.测试

//段名,value 对应数据库的字段值
    @GetMapping("/list")
    public List<Map<String, Object>> userList(){
        String sql = "select * from employee";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    
    //新增一个用户
    @GetMapping("/add")
    public String addUser(){
        //插入语句,注意时间问题
        String sql = "insert into employee(last_name, email,gender,department,birth)" +
                " values ('狂神说','24736743@qq.com',1,101,'"+ new Date().toLocaleString() +"')";
        jdbcTemplate.update(sql);
        //查询
        return "addOk";
    }
 
    //修改用户信息
    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        //插入语句
        String sql = "update employee set last_name=?,email=? where id="+id;
        //数据
        Object[] objects = new Object[2];
        objects[0] = "秦疆";
        objects[1] = "24736743@sina.com";
        jdbcTemplate.update(sql,objects);
        //查询
        return "updateOk";
    }
 
    //删除用户
    @GetMapping("/delete/{id}")
    public String delUser(@PathVariable("id") int id){
        //插入语句
        String sql = "delete from employee where id=?";
        jdbcTemplate.update(sql,id);
        //查询
        return "deleteOk";
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值