springboot+mybatis+druid整合框架实例

maven project整合springboot mybatis druid

源码地址:https://github.com/btredback/springboot-mybatis-druid

  • springboot 快速开发springmvc
  • mybatis 轻量级持久层
  • druid 阿里数据库连接池
  • 数据库当前配置为postgre数据库,可修改依赖driver及datasource配置更换数据库

pom.xml依赖相关内容

因为只做了框架demo,依赖包很少
spring-boot-starter-web -> springmvc和tomcat
spring-boot-starter-test -> 单元测试
mybatis-spring-boot-starter -> mybatis
druid -> druid
postgresql -> 数据库驱动

    
    
        UTF-8
        1.7
        1.1.5
        1.5.6.RELEASE
    
    
    
    
        
            
                
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
        
    

    
        
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
        
            org.springframework.boot
            spring-boot-starter-test
        
        
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        
        
        
        
            com.alibaba
            druid
            ${druid.version}
        
        
        
        
        
        
            postgresql
            postgresql
            9.1-901-1.jdbc4
        
    

整合步骤

  1. 引入相关依赖,pom内容如上
  2. springboot主class声明,也就是springboot的入口application main

@ServletComponentScan 自动扫描servlet的标签,否则标签不起作用,因为druid的内部管理页面是通过servlet声明的,所以需要该标签。
修改为继承SpringBootServletInitializer并重写configure方法,该方法以便打包war时,不通过main进入而是正常web项目使用。

@SpringBootApplication
@ServletComponentScan
public class App extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }

    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}
  1. druid初始化相关配置类,配置参数写于application.properties中

为了使dataSource使用druid的,需要使用@Primary标签,该标签在注入bean时,若找到多个相同bean,则优先注入标签声明的。
druid github项目中有一个自动化配置的druid-springboot-start,如果需要可以使用这个,代替druid依赖,直接配置属性即可。
druid 自动化配置源码class地址

@Configuration
// @PropertySource("classpath:application-test.properties")
@ConfigurationProperties("spring.datasource")
public class DruidDBConfig {
    private String url;
    private String username;
    private String userpassword;
    private String driverClassName;
    private int initialSize;
    private int minIdle;
    private int maxActive;
    private int maxWait;
    private int timeBetweenEvictionRunsMillis;
    private int minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;
    private String filters;
    private String connectionProperties;

    @Bean
    // 声明其为Bean实例
    @Primary
    //如果同一个类型有多个实例,但需要注入一个的时候使用
    // 在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(url);
        datasource.setUsername(username);
        datasource.setPassword(userpassword);
        datasource.setDriverClassName(driverClassName);

        // configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource
                .setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource
                .setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            /*logger.log(Level.ERROR,
                    "druid configuration initialization filter : {0}", e);*/
            e.printStackTrace();
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }
  1. druid内部监控页面配置class

druid内部监控页面写于servlet,直接继承该servlet,然后配置相关属性。当前配置可通过 /druid/index.html访问管理页面

@WebServlet(urlPatterns={"/druid/*"},
initParams={
        @WebInitParam(name="allow",value="127.0.0.1"),// IP白名单(没有配置或者为空,则允许所有访问)
        @WebInitParam(name="deny",value="192.168.1.100"),// IP黑名单 (存在共同时,deny优先于allow)
        @WebInitParam(name="loginUsername",value="admin"),// 用户名
        @WebInitParam(name="loginPassword",value="123456"),// 密码
        @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 8782104600990278875L;

}
  1. application.properties配置druid相关属性及mybatis相关属性
    例如:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=
spring.datasource.userpassword=
spring.datasource.driverClassName=org.postgresql.Driver

#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# MyBatis 配置
mybatis.mapper-locations=classpath*:com/project/springboot_mybatis_druid/mapper/*.xml
mybatis.type-aliases-package=com.project.springboot_mybatis_druid.model
# mybatis.mapper-locations:xml文件扫描位置 
# mybatis.type-aliases-package:Model包扫描位置 
# mybatis.config:mybatis-config.xml配置文件的路径 
# mybatis.typeHandlersPackage:扫描typeHandlers的包 
# mybatis.checkConfigLocation:检查配置文件是否存在 
# mybatis.executorType:设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE
  1. 编写表映射model,dao及其mybatis mapper xml,service,controller
  2. 编写单元测试
  3. 打包jar/war,pom增加build内容

jar打包完成,直接java -jar xxxx.jar即可使用
war打包完成,可放到其他容器中使用(war打包需要把packaging由jar换为war,且将spring-boot-starter-web依赖中的tomcat去除,springboot入口需要继承相关类增加相关重写方法),参考spring-boot guide html

      打包war时需要修改依赖,去除tomcat
      
            org.springframework.boot
            spring-boot-starter-web
            
            
        
    
    
        
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.1
                
                    1.7
                    1.7
                
            
            
            
            
                    
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                1.5.8.RELEASE
                
                    ${start-class}
                    ZIP
                    
                    -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005       
                
                
                    
                        
                            repackage
                        
                    
                
            
            
            
            
        
    

你可能感兴趣的:(springboot+mybatis+druid整合框架实例)