springboot整合alibaba/druid

本文档介绍了如何在SpringBoot项目中整合阿里巴巴的Druid数据源,包括配置SpringBoot的版本选择,POM文件中添加依赖,YML文件设置,创建数据源配置类以及Mybatis配置类,最后涉及DAO层的搭建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,用快速建立建立spring boot项目

springboot 版本号为1.5.12和选择相对应的工具(如版本不一致会导致运行错误)

pom.xml中添加

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.9</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

二 添加yml文件

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/dept?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
#   数据源其他配置
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

三 建立config包

3.1 建立dataSourcesConfig类

package cn.vp.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
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.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourcesConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDataSources() {
        return new DruidDataSource();
    }

    /**
     * 配置druid后台管理的servlet
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "admin");
        initParams.put("allow", "");//默认就是允许所有访问
        initParams.put("deny", "192.168.15.21");//禁止访问的ip
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置druid后台管理的filter
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean druidFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParams = new HashMap<>();
        //设置不拦截的路径  *.cs *.js    /druid/*
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        //设置filter拦截 那些请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }


}

3.2 建立MybatisConfig类

package cn.vp.config;

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                //-自动使用驼峰命名属性映射字段   userId    user_id
                configuration.setMapUnderscoreToCamelCase(true);
                //使用列别名替换列名 select user as User
                configuration.setUseColumnLabel(true);
            }
        };
    }


}

四,dao层的建立

package cn.vp.dao;

import cn.vp.entity.Department;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DepartmentDao {

    @Insert("INSERT INTO `Department` (`departmentName`) VALUES (#{departmentName})")
    public int addDepartment(Department department);

    @Delete("DELETE FROM  department where id=#{id}")
    public int deleteById(Integer id);

    @Update("UPDATE `Department` SET `departmentName`=#{departmentName} WHERE (`id`=#{id})")
    public int updateDepartment(Department department);

    @Select("SELECT  * from department where id=#{id}")
    public Department queryById(@Param("id") Integer id);


}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值