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入门(五)——自定义配置
本文来自网易云社区 大部分比萨店也提供某种形式的自动配置.你可以点荤比萨.素比萨.香辣意大利比萨,或者是自动配置比萨中的极品--至尊比萨.在下单时,你并没有指定具体的辅料,你所点的比萨种类决定了所用的 ...
随机推荐
- 【笔记】特征脸(PCA在人脸识别领域的应用)
人脸识别与特征脸(简单介绍) 什么是特征脸 特征脸(Eigenface)是指用于机器视觉领域中的人脸识别问题的一组特征向量,该方法被认为是第一种有效的人脸识别方法. PCA的具体实现思想见 [笔记]主 ...
- 【Java笔记】以并发修改异常为例总结的出错解决办法
先来看出错代码: /*需求: 遍历已有集合 如果在集合中发现存在字符串元素"world" 则在"world"后添加元素"javaee" */ ...
- SQL Server 判断数据库中是否存在表
使用场景 可以反复的执行相同脚本 方式1:查询sysobjects表 if EXISTS (SELECT * from sysobjects WHERE name='test_table') DROP ...
- SpringCloud升级之路2020.0.x版-22.Spring Cloud LoadBalancer核心源码
本系列代码地址:https://github.com/HashZhang/spring-cloud-scaffold/tree/master/spring-cloud-iiford 经过上一节的详细分 ...
- gitlab-ci集成SonarQube代码质量检查
SonarQube是管理代码质量一个开放平台,可以快速的定位代码中潜在的或者明显的错误. docker安装 1.拉取 postgres:docker pull postgres:10 2.拉取sona ...
- .NET Core:处理全局异常
一.前言 在程序设计中,我们会遇到各种各样的异常问题,一个好的异常处理解决方案能够帮助开发者快速的定位问题,也能够给用户更好的用户体验.那么我们在AspNetCore中该如何捕获和处理异常呢?我们以一 ...
- 【springboot】集成Druid 作为数据库连接池
转自:https://blog.csdn.net/cp026la/article/details/86508139 1. 引言 用户的每一次请求几乎都会访问数据库,访问数据库需要向数据库获取链接,而数 ...
- Mysql 中隐式转换
案例一:条件字段函数操作 假设你现在维护了一个交易系统,其中交易记录表 tradelog 包含交易流水号(tradeid).交易员 id(operator).交易时间(t_modified)等字段.为 ...
- Oracle数据库 —— DML完结
时间:2016-8-18 01:17 ----------------------------------------------------------------------------停下休息的 ...
- Linux centos 安装 tomcat 7
一.tomcat 下载 1.官网下载 如下图点击第1个步骤,第2个步骤右键复制链接地址 # 到linux 下执行下载命令 wget http://mirrors.shu.edu.cn/apache/t ...