Java之SpringBoot自定义配置与整合Druid

SpringBoot配置文件

优先级

前面SpringBoot基础有提到,关于SpringBoot配置文件可以是properties或者是yaml格式的文件,但是在SpringBoot加载application配置文件时是存在一个优先级的。优先级如下:

file:./config/			==> 项目路径下的config目录下
file:./ ==> 项目路径下
classpath:/config/ ==> 资源路径下的config目录下
classpath:/ ==> 项目路径下

yaml的多文档配置

yaml可以通过---达到在一个文件中写入多套配置文件的效果

server:
port: 8081
spring:
profiles: dev ---
server:
port: 8082
spring:
profiles: test

@canditionalon注解,Spring底层的注解, 用于判断是否符合条件,符合条件才会自动装配。

扩展SpringMVC

添加自定义视图解析器

ViewResolver 试图解析器,实现了该接口的类都可以称作试图解析器

candidateViews 候选视图,getBestView 得到最优视图

其中有getCandidateViews方法,先遍历所有的视图解析器,之后封装成view对象,添加到candidateViews候选视图解析器数组中。

自定视图解析器需要实现ViewResolver接口并重写resolveViewName方法

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
} public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewNaem, Locale locale) throws Exception {
return null; }
}
}

想自定义其他功能也是同理,按格式写好组件交给SpringBoot自动装配即可。

自定义DruidDataSources

About Druid

Druid:https://github.com/alibaba/druid/

Druid是alibaba开源平台上一个数据库连接池实现,结合了C3P0,DBCP等DB池的优点,同时也有Web监控界面。

Druid可以很好的监控DB池连接和SQL执行的情况,为监控而生的DB连接池。

SpringBoot2.0以上默认使用Hikari数据源,下面记录下如何用SpringBoot整合配置Druid

添加依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>

配置数据源

因为SpringBoot2.0以上默认使用Hikari数据源,所以需要用 spring.datasource.type 指定数据源。

spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源

可以起一个测试类查看

@Test
public void druidTest() throws SQLException {
//查看默认数据源
System.out.println(dataSource.getClass()); //获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection); //close
connection.close(); }

其他配置

具体其他配置可参考官方文档,简单列举一些:

#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

关于监控的配置是Druid特点。比如可配置log4j以及自带wall防止sql注入

Druid配置类

一般在config包下,与自定义组件类似,通过@ConfigurationProperties注解与配置文件中datasource的配置绑定并交给SpringBoot自动装配。

@Configuration
public class DruidConfig { /*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
} }

测试类

@Test
public void druidTest() throws SQLException {
//查看默认数据源
System.out.println(dataSource.getClass()); //获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection); //close
connection.close(); DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize()); }

数据源监控

还是在同一个配置类文件中写入,这里对于审计或者渗透测试中的重点其实就是用户名密码了和其访问限制了

package com.zh1z3ven.hellospringboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map; @Configuration
public class DruidConfig { /*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
} //配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
initParams.put("loginPassword", "123456"); //后台管理界面的登录密码 //后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问 //设置初始化参数
bean.setInitParameters(initParams);
return bean;
} }

配置完后重启项目,访问测试

监控过滤器filter配置

//配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter()); //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams); //"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}

Java之SpringBoot自定义配置与整合Druid的更多相关文章

  1. springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置

    一.整合Druid数据源 Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库 ...

  2. SpringBoot 自定义配置

    有时候需要自己定义一些配置,比如SpringBoot没有提供Druid连接池的配置,需要我们自己写配置. 以在springboot中使用Druid为例. 依赖 <dependency> & ...

  3. SpringBoot自定义配置以及IDEA配置提示

    本篇文章将会讲解在springboot项目中如何实现自定义配置以及在IDEA或者Eclipse中实现配置项提示,就像spring的配置提示一样 想要做到这点其实非常简单 1.添加依赖 <depe ...

  4. springboot自定义配置信息读取

    在properties配置文件加入自定义配置例如: zxgl.detail.url=http://*****/zxgl-web/news/viewNewsIndexDetail.do?id= #资讯t ...

  5. SpringBoot自定义配置步骤

    1. 在yml中填写自定义配置 ly: sms: accessKeyId: # 短信配置 accessKeySecret: signName: xx商城 # 签名名称 verifyCodeTempla ...

  6. 微服务之springboot 自定义配置(一)Application配置文件

    配置的文件的格式 springboot可以识别两种格式的配置文件,分别是yml和properties 文件.我们可以将application.properties文件换成application.yml ...

  7. springboot自定义配置源

    概述 我们知道,在Spring boot中可以通过xml或者@ImportResource 来引入自己的配置文件,但是这里有个限制,必须是本地,而且格式只能是 properties(或者 yaml). ...

  8. SpringBoot#自定义配置的封装

    _震惊,开局 不可避免的需要弄一些自定义的配置. 要点: 1. 把配置项都写出来,分析层次关系:2. 抽象成bean与bean之间的关系,写出bean对应的类,这时候配置项对应了bean的属性,属性可 ...

  9. SpringBoot入门(五)——自定义配置

    本文来自网易云社区 大部分比萨店也提供某种形式的自动配置.你可以点荤比萨.素比萨.香辣意大利比萨,或者是自动配置比萨中的极品--至尊比萨.在下单时,你并没有指定具体的辅料,你所点的比萨种类决定了所用的 ...

随机推荐

  1. pikachu Unsafe Fileupload

    不安全的文件上传漏洞概述文件上传功能在web应用系统很常见,比如很多网站注册的时候需要上传头像.上传附件等等.当用户点击上传按钮后,后台会对上传的文件进行判断 比如是否是指定的类型.后缀名.大小等等, ...

  2. 013 PCIe体系结构的组成部件

    一.PCIe体系结构的组成部件 PCIe总线作为处理器系统的局部总线,其作用与PCI总线类似,主要目的是为了连接处理器系统中的外部设备,当然PCIe总线也可以连接其他处理器系统.在不同的处理器系统中, ...

  3. Oracle 11g数据库下载安装教程

    今天重装系统之后发现甲骨文的网站变化较大,下载安装废了一点时间,留下个笔记为以后再装留作参考.本教程是win10,64位系统环境下 1.下载 下载的时候需要登陆甲骨文账号,如果没有的话申请一个也挺快. ...

  4. Spring系列之多个数据源配置

    前言 在上篇文章讲到了如何配置单数据源,但是在实际场景中,会有需要配置多个数据源的场景,比如说,我们在支付系统中,单笔操作(包含查询.插入.新增)中需要操作主库,在批量查询或者对账单查询等对实时性要求 ...

  5. Xilinx约束学习笔记(二)—— 定义时钟

    2. 定义时钟 2.1 关于时钟 为了获得最佳精度路径覆盖信息,必须正确定义时钟. 时钟要定义在时钟树的根 pin 或 port 上,称为 source point. 时钟的边缘应该由周期和波形进行组 ...

  6. 【java虚拟机】类加载机制

    作者:平凡希 原文地址:https://www.cnblogs.com/xiaoxi/p/6959615.html 一.什么是类的加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中, ...

  7. 深入理解Java类加载器(二):线程上下文类加载器

    摘要: 博文<深入理解Java类加载器(一):Java类加载原理解析>提到的类加载器的双亲委派模型并不是一个强制性的约束模型,而是Java设计者推荐给开发者的类加载器的实现方式.在Java ...

  8. 刷题-力扣-518. 零钱兑换 II

    518. 零钱兑换 II 题目链接 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/coin-change-2/ 著作权归领扣网络所有.商业转载 ...

  9. Kickstart部署之NFS架构

    原文转自:https://www.cnblogs.com/itzgr/p/10200615.html作者:木二 目录 一 准备 1.1 完整架构:Kickstart+DHCP+NFS+TFTP+PXE ...

  10. Windows系统定时备份MySQL数据库

    当一个网站投入使用时,定期备份数据库是必要的事.那么,在Windows系统上,我们该如何做呢? 如下语句可以实现备份及还原MySQL数据库: 备份MySQL数据库 mysqldump -uroot - ...