太妙了!Spring boot 整合 Mybatis Druid,还能配置监控?
阅读原文时间:2022年04月14日阅读:1
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.16</version>
</dependency>
<!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
<!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
如果使用log4j需要添加log4j的依赖并且排除本身slf4j
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <version>1.3.8.RELEASE</version>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
   <!--排除本身日志-->
     <exclusions>
         <exclusion>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-logging</artifactId>
         </exclusion>
     </exclusions>
</dependency>

​ 附上log4j.properties的配置

# LOG4J rootCategory config
# 控制台输出
log4j.rootLogger=INFO, file, console
LocationInfo =true
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM HH:mm:ss} %5p %c{1}:%L - %m%n
# 日志文件
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=logs/springboot.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM HH:mm:ss} %5p %c{1}:%L - %m%n

dao

import com.ljy.sys.entity.User;

import java.util.List;

public interface SysUserMapper {
    List<User> findAll();
}

Mapper

service及其实现类

import com.ljy.sys.entity.User;

import java.util.List;

public interface SysUserService {
    List<User> findAll();
}



import com.ljy.sys.dao.SysUserMapper;
import com.ljy.sys.entity.User;
import com.ljy.sys.model.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
/**
 * SysUserService实现类
 * @author ljy&jcq
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<User> findAll() {
        return sysUserMapper.findAll();
    }
}

controller

import com.ljy.sys.model.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/findAll")
    public Object findAll(){
        return sysUserService.findAll();
    }
}



import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * mybatis 配置类
 * @author ljy&jcq
 * MapperScan 扫描dao
 *
 */
@Configuration
@MapperScan("com.ljy.sys.**.dao")
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //扫描service层
        sqlSessionFactoryBean.setTypeAliasesPackage("com.ljy.sys.**.model");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //扫描映射文件 Mapper文件所在的地址
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/templates/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
}



//表示在应用启动时自动扫描com.ljy.sys包下的内容,当然Spring Boot也会自动扫描启动类包及其子包,这里不设置也是可以自动扫描的
@SpringBootApplication(scanBasePackages = {"com.ljy.sys"})
public class SysApplication {
    public static void main(String[] args) {
        SpringApplication.run(SysApplication.class, args);
    }
}



spring:
  datasource:
    #数据库连接配置
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/salery?serverTimezone=GMT%2B8&characterEncoding=UTF-8
    username: root
    password: root
    #连接池配置
    initial-size: 5  # 初始化大小
    min-idle: 5  # 最小
    max-active: 100  # 最大
    max-wait: 60000  # 连接超时时间
    time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
    validationQuery: selectversion()
    test-while-idle: true  # 当连接空闲时,是否执行连接测试
    test-on-borrow: false  # 当从连接池借用连接时,是否测试该连接
    test-on-return: false  # 在连接归还到连接池时是否测试该连接
    filters: wall,stat,log4j  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,log4j使用哪种日志系统就添加哪种
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    maxOpenPreparedStatements: 20
    connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true



import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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 org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 *  druid的配置类
 * @author jcq&ljy
 */
@Configuration
public class DruidConfig {
    @Bean(name = "dataSource")
    //这里使用的是自动注入spring.datasource下的各种属性,如需要自定义配置,可新建配置类使用
    //自定义配置类类名上添加@ConfigurationProperties(prefix = "spring.datasource.druid")导入yml中设置的数据
    //在本配置类上加入@EnableConfigurationProperties({自定义.class}) 导入自定义配置 在本方法中手动set注入 参考注释的方法
    @ConfigurationProperties("spring.datasource")
    @Primary
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
        /**
     *     手动set注入
     *     @Bean
     *     public DataSource druidDataSource() {
     *         DruidDataSource datasource = new DruidDataSource();;
     *         datasource.setUrl(properties.getUrl());
     *         datasource.setUsername(properties.getUsername());
     *         datasource.setPassword(properties.getPassword());
     *         datasource.setDriverClassName(properties.getDriverClassName());
     *         datasource.setInitialSize(properties.getInitialSize());
     *         datasource.setMinIdle(properties.getMinIdle());
     *         datasource.setMaxActive(properties.getMaxActive());
     *         datasource.setMaxWait(properties.getMaxWait());
     *         datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
     *         datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
     *         datasource.setValidationQuery(properties.getValidationQuery());
     *         datasource.setTestWhileIdle(properties.isTestWhileIdle());
     *         datasource.setTestOnBorrow(properties.isTestOnBorrow());
     *         datasource.setTestOnReturn(properties.isTestOnReturn());
     *         properties.setPoolPreparedStatements(properties.isPoolPreparedStatements());
     *         properties.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
     *         properties.setFilters(properties.getFilters());
     *         return datasource;
     *     }
     */

    /**
     * 配置Druid的监控,一个管理后台的Servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        //指定拦截器只拦截druid管理页面的请求
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单,如果没有设置或为空,则表示允许所有访问.(不能写成*,不然会报错)
        servletRegistrationBean.addInitParameter("allow", "");
        // IP黑名单(共同存在时,deny优先于allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.19");
        //控制台管理的用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置一个web监控的filter
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}

输入配置类中设置的账号密码,就可以看到如下界面:

但是打开数据源显示如下:

不要担心,只需要向刚才的我们写好的controller发送一次请求即可,发送了请求后结果如下:

​ 尤其需要注意:

​ 如果这一行显示为空,需要检查监听器配置或日志系统是否和yml中的配置匹配。

​ 如果spring监控为空,是因为我们没有设置切面,我们需要设置切面

import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * spring监控配置切面
 * @author jcq&ljy
 */
@Configuration
public class SpringDaoMethodAspect {
    @Bean
    public DruidStatInterceptor druidStatInterceptor(){
        return new DruidStatInterceptor();
    }
    @Bean
    public JdkRegexpMethodPointcut druidStatPointcut(){
        JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut();
        String patterns = "com.ljy.*.*.service.*";
        String patterns2 = "com.ljy.*.*.dao.*";
        druidStatPointcut.setPatterns(patterns,patterns2);
        return druidStatPointcut;
    }
    @Bean
    public Advisor druidStatAdvisor() {
        return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor());
    }
}

注:如果仍为空,先检查是否导入了aop的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

最后附上成功截图

大家看完有什么不懂的可以在评论区留言,觉得对你有帮助的话可以给我点个赞!