SpringBoot--整合Mybatis+druid


  分為兩部分,首先替換默認數據源為阿里德魯伊並添加監控,其次是SpringBoot下使用Mybatis

替換數據源為德魯伊

  首先在配置文件里配置好數據庫連接的基本信息,如username password url等,重要的是把默認的type換成Druid。這樣做數據源已經換成druid了,但是如果想完成對druid的定制化設置如設置initialSize,僅僅在yml里配置是不可以的,需要再實現一個配置類,並在這個配置類里實現后台監控的配置。

spring:
  datasource:
    username: root
    password: password
    url: jdbc:mysql://localhost:3306/javaweb
    driver-class-name: com.mysql.jdbc.Driver
   # initialization-mode: always
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
  • 標注@Configuration表示這是一個注解,使用@Bean向容器里添加Bean,Bean的類型是DataSource
  • 添加@ConfigurationProperties(prefix="spring.dataSource"),這樣在yml里關於druid的配置才能生效
  • 以向容器中添加Servlet和Filter的形式為druid添加后台監控,並添加相應的配置
@Configuration
public class DruidConfig {

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

    //配置druid監控
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        HashMap<String, String> map = new HashMap<>();
        map.put("loginUsername","admin");
        map.put("loginPassword","123456");
        bean.setInitParameters(map);

        return bean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        HashMap<String, String> map = new HashMap<>();
        map.put("exclusions","*.js");
        bean.setInitParameters(map);
        bean.setUrlPatterns(Arrays.asList("/*"));

        return bean;
    }

}

整合Mybatis

  編寫接口和接口實現類xml文件和普通使用Mybatis沒有區別,關鍵在於讓SpringBoot接口的實現類的位置,和Mybatis配置文件的位置。需要在yml里告訴SpringBoot具體的位置,其中config-location對應配置文件的位置,mapper-locations對應接口實現類的位置。為了使項目整潔,兩個配置文件我都放在了resources/mybatis下。

  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM