SpringBoot (2) yaml,整合项目

1 YAML配置文件

        SpringBoot采用集中化配置管理,即将所有配置都写在application.properties中,但当配置增多后,会出现"难阅读,层级结构模糊"的问题

        于是出现了application.yaml.yml配置文件,用于替代application.properties配置文件

1.1 书写规则

        (1) 区分大小写

        (2) K和V之间用 : +空格分隔

        (3) 缩进表示层级关系,同一层级有相同的缩进

        (4) #表示注释

1.2 代码示例

server:
  port: 8083  #自定义 端口
  servlet:
    context-path: /sb  #项目地址

spring:
  application:
    name: engineering  #微服务名称
  profiles:
    active: dev,test
  main:
    allow-circular-references: true #开启spring解决"循环依赖"
  web:
    resources:
      static-locations: classpath:/a/,classpath:/b/ #废掉4个"静态访问路径",自定义a,b文件夹为新的"静态访问路径"
  mvc:
    static-path-pattern: /html/** #访问"静态访问路径"中的静态文件,需要加html前缀(index.html不用加前缀)
  servlet:
    multipart:
      max-file-size: 20MB  #(文件上传)最大文件大小
      max-request-size: 30MB  #请求大小限制
  datasource: #mysql数据源
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource  #SpringBoot(默认)数据源,如果使用其他数据源需(dbcp2等)要额外导包
    url: jdbc:mysql://localhost:3306/sunner?rewriteBatchedStatements=true
    username: root
    password: root
  data:
    redis:
      host: localhost  #docker容器:redis_container_6379
      port: 6379
      password: #默认为空,如果有设置按设置的来
      timeout: 1000 #连接超时时间(ms)
      jedis:
        pool:
          max-active: 50 #连接池最大连接数,-1表示无限制
          max-idle: 30 #连接池最大空闲连接数
          min-idle: 0 #连接池最小空闲连接数
          max-wait: -1 #连接池最大阻塞等待时间(-1表示无限制)

logging: #指定logback配置文件(配置文件不要用logback.xml,而是用logback-xxx.xml)
  config: classpath:logback-dev.xml

mybatis:
  mapper-locations: classpath:com/sunner/dao/*Dao.xml  #映射配置文件
  type-aliases-package: xyz.aboluo.pojo  #mybatis(包)起别名

mybatis-plus:
  mapper-locations: "classpath*:xyz/aboluo/engineering/dao/*Dao.xml"  #映射配置文件
  type-aliases-package: xyz.aboluo.mybatisPlus.pojo  #mybatis(包)起别名
  configuration:
    map-underscore-to-camel-case: true #(默认)开启驼峰和下划线的映射
    cache-enabled: false #(默认)关闭二级缓存
  global-config: #全局配置,优先级不如注解配置高,但如果pojo类没有使用注解,则"全局配置"生效
    db-config:
      id-type: assign_id #(默认)id为雪花算法生成
      update-strategy: not_null #更新策略:(默认)只更新非空字段

--- #用三条短横线可以将下面的配置全部缩进

1.3 用yaml进行复杂数据绑定

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Date birthday;
    private Boolean manFlag;
    private Child child;  //嵌套对象
    private List<Dog> dogs;  //嵌套数组
    private Map<String,Cat> cats;  //嵌套map
}

person:
  name: 王老五
  age: 35
  birthday: 1996/05/02 12:05:06  #(默认)只能用这种格式
  manFlag: true  #对于驼峰命名的属性也可以小写用-分隔  例如man-flag
  child:
    name: 王老六
    age: 8
  dogs:
    - name: 旺财
      age: 1
      like: 骨头
    - name: 小黑
      age: 3
      like: 鸡肉
  cats:
    cat1:
      name: 喵桑
      age: 5
      like: 猫粮
    cat2: { name: 咪咪,age: 4,like: 鱼罐头 }

2 整合日志

日志门面(接口)采用slf4j,日志实现采用Logback

这些已经被SpringBoot默认整合了,无需我们再做额外的操作

2.1 日志配置

        可以在application.yaml中配置(不推荐)

        或者使用logback的配置文件logback.xml(推荐),具体可以看这篇文章

3 整合web

3.1 默认配置

        (1) 默认静态资源处理:静态资源放在static文件夹(或resources、public文件夹)下可以被直接访问

                4个静态资源访问路径:classpath:/META-INF/resources/

                                                    classpath:/resources/

                                                    classpath:/static/

                                                    classpath:/public/

        (2) 支持放在4个静态访问路径中的index.html当做首页展示

        (3) 自动注册了Converter(类型转换器),Formatter(格式化)组件,例如在yaml配置文件中可以帮我们将字符串转换为Integer、对象、数组等,也可以将日期字符串(默认只能是yyyy/MM/dd ss:mm:ss:SSS的格式)格式化成Date对象

        (4) 支持HttpMessageConverters,用于将返回的对象转为json,即对@ResponseBody注解的支持

        (5) 自动使用ConfigurableBuildingInitializer,实现数据校验、类型转换、数据绑定功能,即对@RequestParameter、@RequestBody等注解的支持

3.2 web应用开发方式

3.2.1 全自动

        完全按照SpringBoot的默认配置

3.2.2 全手动

        在Spring配置类(@Configuration或@SpringBootConfiguration)上添加@EnableWebMvc,禁止所有默认配置

3.2.3 手自一体(推荐)

        修改配置可以用yaml配置文件的方式

        也可以用Spring配置类的方式: 用Spring配置类实现WebMvcConfigurer,但千万不要标@EnableWebMvc,重写需要修改配置的方法

@SpringBootConfiguration
@EnableConfigurationProperties({Dog.class, Cat.class})
public class SpringConfig implements WebMvcConfigurer {
    /**
     * 配置静态资源的方法
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 自定义配置
        registry.addResourceHandler("/html/**")
                //所有以html开头的请求都会去"静态访问路径"a和b下面匹配
                .addResourceLocations("classpath:/a/", "classpath:/b/")
                //设置静态资源缓存规则(超过1000秒重新获取静态资源)
                .setCacheControl(CacheControl.maxAge(1000, TimeUnit.SECONDS));
    }
}

        还可以用将WebMvcConfigurer注册进SpringIOC容器的方式

@SpringBootConfiguration
@EnableConfigurationProperties({Dog.class, Cat.class})
public class SpringConfig {
    @Bean
    public WebMvcConfigurer getWebMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                // 自定义配置
                registry.addResourceHandler("/html/**")
                        //所有以html开头的请求都会去"静态访问路径"a和b下面匹配
                        .addResourceLocations("classpath:/a/", "classpath:/b/")
                        //设置静态资源缓存规则(超过1000秒重新获取静态资源)
                        .setCacheControl(CacheControl.maxAge(1000, TimeUnit.SECONDS));
            }
        };
    }
}

4 整合mybatis

4.1 导包

<dependencies>>
	<!--mybatis-->
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>3.0.2</version>
	</dependency>
	<!--mysql驱动-->
	<dependency>
		<groupId>com.mysql</groupId>
		<artifactId>mysql-connector-j</artifactId>
		<version>8.0.33</version>
	</dependency>
</dependencies>

        mybatis-spring-boot-starter依赖了spring-boot-starter-jdbc(我们知道jdbc是用来操作数据库的),其中为我们自动配置好的:

                (1) org.springframework.boot.autoconfigure.jdbc.jdbcTemplateAutoConfiguration是对数据源的自动配置(默认使用HikariDataSource)

                (2) org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration是用来操作数据库的,但也可以选择整合mybatis

                (3) org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration用于支持事务(支持@Transactional)

4.2 application.yaml

        配置mysql数据源

        配置mybatis映射配置文件,类(包)别名

4.3 dao接口+mapper.xml

4.4 dao接口包扫描

        在Spring配置类@MapperScan扫描到dao接口

5 整合redis

5.1 导包

        (看之前文章)

5.2 配置yaml

        (看之前文章)

5.3 StringRedisTemplate

        使用@Autowired进行依赖注入后即可使用

5.3.1 常用方法

●判断

        stringRedisTemplate.hasKye(String key)  //检查key是否存在

●存储

        stringRedisTemplate.opsForValue().set(String key,String value)  //存储key,value

        stringRedisTemplate.opsForValue().set(String key,String value,Duration timeout)  //存储key,value,有效时间

●获取

        stringRedisTemplate.opsForValue().get(Object key)  //获取value

        stringRedisTemplate.opsForValue().get(String key,long start,long end)  //截取value(包含2个下标)

●删除

        stringRedisTemplate.delete(String key)  //删除缓存

●有效时间

        stringRedisTemplate.expire(String key,Duration timeout)  //设置有效时间

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值