Java之SpringBoot自定义配置与整合Druid
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的更多相关文章
- springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置
一.整合Druid数据源 Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库 ...
- SpringBoot 自定义配置
有时候需要自己定义一些配置,比如SpringBoot没有提供Druid连接池的配置,需要我们自己写配置. 以在springboot中使用Druid为例. 依赖 <dependency> & ...
- SpringBoot自定义配置以及IDEA配置提示
本篇文章将会讲解在springboot项目中如何实现自定义配置以及在IDEA或者Eclipse中实现配置项提示,就像spring的配置提示一样 想要做到这点其实非常简单 1.添加依赖 <depe ...
- springboot自定义配置信息读取
在properties配置文件加入自定义配置例如: zxgl.detail.url=http://*****/zxgl-web/news/viewNewsIndexDetail.do?id= #资讯t ...
- SpringBoot自定义配置步骤
1. 在yml中填写自定义配置 ly: sms: accessKeyId: # 短信配置 accessKeySecret: signName: xx商城 # 签名名称 verifyCodeTempla ...
- 微服务之springboot 自定义配置(一)Application配置文件
配置的文件的格式 springboot可以识别两种格式的配置文件,分别是yml和properties 文件.我们可以将application.properties文件换成application.yml ...
- springboot自定义配置源
概述 我们知道,在Spring boot中可以通过xml或者@ImportResource 来引入自己的配置文件,但是这里有个限制,必须是本地,而且格式只能是 properties(或者 yaml). ...
- SpringBoot#自定义配置的封装
_震惊,开局 不可避免的需要弄一些自定义的配置. 要点: 1. 把配置项都写出来,分析层次关系:2. 抽象成bean与bean之间的关系,写出bean对应的类,这时候配置项对应了bean的属性,属性可 ...
- SpringBoot入门(五)——自定义配置
本文来自网易云社区 大部分比萨店也提供某种形式的自动配置.你可以点荤比萨.素比萨.香辣意大利比萨,或者是自动配置比萨中的极品--至尊比萨.在下单时,你并没有指定具体的辅料,你所点的比萨种类决定了所用的 ...
随机推荐
- Git(6)-- 记录每次更新到仓库(git clone、status、add、diff、commit、rm、mv命令详解)
@ 目录 1.克隆现有仓库:git clone 2.检查当前文件状态 :git status 3.跟踪新文件:git add 4.暂存已修改的文件:git add 5.状态简览: git status ...
- 【Vulnhub】DC-1靶机
一.信息收集 1.1 环境 kali : 192.168.124.141 DC-1 : 192.168.124.150 1.2 nmap进行扫描 :nmap -sV 192.168.124.150 I ...
- XSS之防御与绕过
很久之前的随笔讲过XSS的编码绕过的一些内容 本次侧重整理一下常见的防御思路,顺便补充一些针对性的绕过思路以及关于XSS个人想到的一些有趣的事情 开篇之前,先看一下XSS介绍(包括mXSS.uXSS. ...
- Linux部署达梦数据库(完全版)
环境准备 数据库下载去http://www.dameng.com 1.下载好达梦数据库iso上传(通过xftp)到你自己存在的目录(/opt) 2.将你上传的iso文件挂载到其它的目录下面(mount ...
- NOIP 模拟 9 考试总结
T1 一道推规律的题,没想出来,暴力打得常数还太大了,挂了不少 题解 T2 这是一道二分题,很巧妙,但是对于想我一样懒得人,那个数据结构就水过去了 (裸的分块加强大的卡长和合适的块的大小可以卡过去) ...
- Ubuntu时间有误差,设置系统时间与网络时间同步
转载地址:https://blog.csdn.net/qq_33733970/article/details/78823620
- 异步编程之EAP
一.概述 前面我们了解到了APM编程模式,但APM不支持对异步操作的取消和没有提供对进度报告的功能. 对于界面程序来说,进度报告和取消操作的支持也是必不可少的,为了支持这些功能,微软在.NET 2.0 ...
- uwp 中的动画
xml --------------------------------------- <Page x:Class="MyApp.MainPage" xmlns=" ...
- 【转】CAP定理的含义
转自:https://blog.csdn.net/pengjunlee/article/details/86517935 1998年,加州大学的计算机科学家 Eric Brewer 提出了分布式系统的 ...
- 使用dom4j工具:获得文本内容(四)
package dom4j_read; import java.io.File; import org.dom4j.Document; import org.dom4j.Element; import ...