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. 【笔记】numpy.array的常用基本运算以及对数据的操作

    numpy.array的基本运算以及对数据的操作 设置一个问题,例如 这种只需要基本的运算就可以实现 类似的 numpy对向量的运算进行了优化,速度是相当快的,这种被称为universal funct ...

  2. CAS 5.3服务器搭建

    一.本例环境说明 JDK 1.8 CAS 5.3 apache-maven-3.6.0 二.CAS安装步骤 2.1 提前安装好JDK和Maven环境 安装步骤略 2.2 CAS环境搭建 2.2.1 C ...

  3. S3C2440—6.串口的printf实现

    文章目录 一.框架 二.printf函数原理 2.1 printf的声明 2.2 参数解读 2.3 如何得到可变参数的值 2.4 解决变参的宏定义 2.5 完成printf函数的封装 三.结合UART ...

  4. noip35

    T1 考场乱搞出锅了... 正解: 把原序列按k往左和往右看成两个序列,求个前缀和,找下一个更新的位置,直接暴跳. Code #include<cstdio> #include<cs ...

  5. 聊一聊中台和DDD(领域驱动设计)

    本次分享价值:本次分享主要针对中台.微服务和领域模型的理念.本质及其构建方法论进行探讨.对领域分析的价值所在就是寻求"千变万化"中相对的"稳定性.第一性",然后 ...

  6. 【SpringMVC】@RequestMapping注解

    @RequestMapping注解的源码 @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNT ...

  7. PQGrid商业化的表格组件

    官网地址https://paramquery.com/pro/grid 右侧导航条有目录哟,看着更方便 快速入门 表格构建 API简单介绍 主要研究功能介绍 快速入门 ParamQuery Grid ...

  8. servlet+Ajax开发web工程

    前言 因为目前基本已经不会再用到servlet+jsp开发项目了,基本都是使用框架来开发:我们常用的框架都是基于servlet来封装的,该阶段只需要了解一下tomcat如何使用,servlet的生命周 ...

  9. 分享几个下载豆瓣资源的chrome插件

    最近chrome终于以4.69%的市场占有率击败firefox成为中国第二大浏览器.(第一当然是争霸宇宙的IE了) 虽然chrome官方应用程序商店有不少豆瓣的辅助插件,但大多没什么用.属于蛋疼插件. ...

  10. eclipse 将本地插件引用(多种方法)

    eclipse 将本地插件引用(多种方法) 因为工作原因需要使用eclipse,而接触的项目需要一个eclipse的插件才可以进行一些特殊的使用,但是因为年久用的人也少,我解压原先带有插件版本的ecl ...