码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot+Mybatis+Durid

时间:2018-10-19 20:16:03      阅读:736      评论:0      收藏:0      [点我收藏+]

标签:XML   conf   pem   定义   记录   用户   配置数据源   pass   man   

以下内容用于记录目的。实现在Springboot中集成Mybatis和Druid。其中使用的为spring-boot-starter-parent如下:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

1,引入需要的依赖

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.8</version>
</dependency>
<dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.2</version>
</dependency>
<dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.6</version>
</dependency>
<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.4</version>
</dependency>

2,application.yml中配置数据源信息

spring: 
  datasource: 
    master:
      driverClassName: oracle.jdbc.OracleDriver
      url: jdbc:oracle:thin:@192.168.30.150:1521:orcl
      username: ioss_sqm
      password: ioss_sqm

3,创建用于封装数据源配置信息的对象DruidPropConfig

public class DruidPropConfig {
    private String url ;
    private String driverClassName ;
    private String username ;
}

4,创建用于判断是否需要创建数据源的Condition对象

public class MasterDataSourceCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata arg1) {
        if(!context.getEnvironment().containsProperty("spring.datasource.master.url")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.driverClassName")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.username")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.password")){
            return false ;
        }
        String url = context.getEnvironment().getProperty("spring.datasource.master.url") ;
        String driverClassName = context.getEnvironment().getProperty("spring.datasource.master.driverClassName") ;
        String username = context.getEnvironment().getProperty("spring.datasource.master.username") ;
        String password = context.getEnvironment().getProperty("spring.datasource.master.password") ;
        if(StringUtils.isNotBlank(url) && StringUtils.isNotBlank(driverClassName) 
                && StringUtils.isNotBlank(username)&& StringUtils.isNotBlank(password)){
            return true ;
        }
        return false;
    }
}

5,配置数据源

@Configuration 
@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@Conditional(MasterDataSourceCondition.class)
@MapperScan(basePackages = "com.ultrapower.ioss.cmnet.linksync.mapper", sqlSessionTemplateRef="sqlSessionTemplate")
public class MasterDataSourceCfg{

    private Logger log = LoggerFactory.getLogger(MasterDataSourceCfg.class) ;

    public PageInterceptor pageHelper() {
        PageInterceptor pageHelper = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("autoRuntimeDialect", "true");
        // properties.setProperty("params","pageNum=pageNum;pageSize=pageSize");
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    @Primary
    @Bean(name = "datasourceConfig")
    @ConfigurationProperties(prefix="spring.datasource.master")
    public DruidPropConfig datasourceConfig(){
        return new DruidPropConfig();
    }

    /**
     * 主数据库数据源
     * */
    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() throws Exception{
        DruidPropConfig config = datasourceConfig();
        if(config == null || config.getDriverClassName() == null){
            throw new Exception("slave datasource 数据源需要配置." + config.toString());
        }
        /*
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(config.getDriverClassName());
        dataSource.setUrl(config.getUrl());
        dataSource.setUsername(config.getUsername());
        dataSource.setPassword(config.getPassword());
        dataSource.setConnectionErrorRetryAttempts(5);
        return dataSource;
        */
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, config.getDriverClassName());
        properties.put(DruidDataSourceFactory.PROP_URL, config.getUrl());
        properties.put(DruidDataSourceFactory.PROP_USERNAME, config.getUsername());
        properties.put(DruidDataSourceFactory.PROP_PASSWORD, config.getPassword());
        // 添加统计、SQL注入、日志过滤器
        properties.put(DruidDataSourceFactory.PROP_FILTERS, "stat,wall,log4j2");
        // sql合并,慢查询定义为5s
        properties.put(DruidDataSourceFactory.PROP_CONNECTIONPROPERTIES, "druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
        return DruidDataSourceFactory.createDataSource(properties);
    }

    @Primary
    @Bean(name = "sqlSessionFactory")
    @ConditionalOnBean(name = "dataSource") // 仅仅在当前上下文中存在某个对象时,才会实例化一个Bean
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //bean.setObjectWrapperFactory(new MapWrapperFactory());
        bean.setDataSource(dataSource);
        // bean.setPlugins(new Interceptor[] {
        // pageHelper(),sqlPrintInterceptor() });
        bean.setPlugins(new Interceptor[] { pageHelper() });
        // 添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            List<Resource> resources = new ArrayList<>();
            resources.addAll(Arrays.asList(resolver.getResources("classpath*:com/ultrapower/ioss/**/mapper/**/*.xml")));
            resources.addAll(Arrays.asList(resolver.getResources("classpath:mapper/**/*.xml")));
            bean.setMapperLocations(resources.toArray(new Resource[resources.size()]));
            // 设置mybatis configuration 扫描路径
            // bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Primary
    @Bean("sqlSessionTemplate")
    @ConditionalOnBean(name = "sqlSessionFactory")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @ConditionalOnBean(name = "dataSource")
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }
}

6,配置Durid监控

@Configuration
public class DruidConfiguration {

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        // IP白名单
        //servletRegistrationBean.addInitParameter("allow", "192.168.2.25,127.0.0.1");
        // IP黑名单(共同存在时,deny优先于allow)
        //servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        // 控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        // 是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

Springboot+Mybatis+Durid

标签:XML   conf   pem   定义   记录   用户   配置数据源   pass   man   

原文地址:http://blog.51cto.com/dengshuangfu/2306660

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!