美文网首页
Spring Boot整合Mybatis、Quartz项目的经验

Spring Boot整合Mybatis、Quartz项目的经验

作者: cjp1016 | 来源:发表于2016-12-10 21:21 被阅读0次

    1.SpringBoot整合mybatis说明

    项目目录结构


    Paste_Image.png

    1.pom.xml

    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.2.RELEASE</version>
    </parent>
       <properties>
            <!-- main properties -->
            <spring.version>4.3.4.RELEASE</spring.version>
            <mybatis.version>3.4.0</mybatis.version>
            <mybatis-spring.version>1.3.0</mybatis-spring.version>
            <quartz.version>2.2.1</quartz.version>
            <httpclient.version>4.3.6</httpclient.version>
            <guava.version>18.0</guava.version>
    
            <!-- other properties -->
            <oracle.driver.version>10.2.0.4.0</oracle.driver.version>
            <druid.version>1.0.15</druid.version>
            <junit.version>4.11</junit.version>
    
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <java.version>1.7</java.version>
        </properties>
      <dependencies>
            <!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc。 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- 支持Spring Test -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
            </dependency>
            <!-- Mybatis数据库连接 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis-spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- Quartz -->
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>${quartz.version}</version>
            </dependency>
    
            <!-- jdbc driver -->
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc14</artifactId>
                <version>${oracle.driver.version}</version>
            </dependency>
    
            <!-- connection pool -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
    
    </dependencies>
    

    2.Application.java

    @ComponentScan
    @EnableAutoConfiguration
    @SpringBootApplication
    public class Application {
        
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
        
    }
    

    3.Config包里面的配置
    dataSource的配置,Enviroment加载的是resource目录下的application.properties

    @Configuration
    public class DruidConfig {
        
        private static Logger logger = LoggerFactory.getLogger(DruidDataSource.class);
        
        @Autowired
        Environment env;
        
        @Bean
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(env.getProperty("jdbc.driverClassName"));
            ds.setUrl(env.getProperty("jdbc.url"));     
            ds.setUsername(env.getProperty("jdbc.username"));
            ds.setPassword(env.getProperty("jdbc.password"));
            try {
                ds.setFilters("stat,wall");
            } catch (SQLException e) {
                e.printStackTrace();
                logger.error("druid error:{} ",e);
            }
            return ds;
        }
        
    }
    

    Mybatis的扫描配置

    /**
     * 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
     * 而且因为SpringBoot优先加载MyBatisMapperScannerConfig,所以必须跟MybatisConfig分开
     * @author cjp
     * @date 2016年12月8日
     */
    @Configuration
    @AutoConfigureAfter(MybatisConfig.class)
    public class MyBatisMapperScannerConfig {
        
        /**
         * mybatis扫描的dao
         */
        private static String MYBATIS_DAO = "com.whty.**.client.dao";
        
        /**
         * 动态自动装配
         * @return
         */
        @Bean
        public static MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer mapperConfig = new MapperScannerConfigurer();
            mapperConfig.setSqlSessionFactoryBeanName("sqlSessionFactory");
            mapperConfig.setBasePackage(MYBATIS_DAO);
            return mapperConfig;
            
        }
    }
    
    /**
     * Mybatis连接配置,实现事务配置
     * @author cjp
     * @date 2016年12月8日
     */
    @Configuration
    @EnableTransactionManagement
    public class MybatisConfig{
        
        private static Logger logger = LoggerFactory.getLogger(MybatisConfig.class);
        
        @Autowired
        private DataSource dataSource;
        
        /**
         * mybatis.xml配置文件
         */
        private static String MYBATIS_CONFIG = "/mybatis/mybatis-config.xml";
        /**
         * mapper.xml配置文件
         */
        private static String MYBATIS_MAPPER = "/mybatis/mappers/**.xml";
        /**
         * model-package扫描的model
         */
        private static String MYBATIS_MODEL = "com.whty.**.client.models";
        
        
        /**
         * Mybatis-SqlSessionFactory初始化
         * @return
         */
        @Bean
        public SqlSessionFactory sqlSessionFactory(){
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            //解决Mybatis-springboot打包jar找不到对应class问题
            VFS.addImplClass(SpringBootVFS.class);
            bean.setDataSource(dataSource);
            bean.setTypeAliasesPackage(MYBATIS_MODEL);
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            try {
                bean.setMapperLocations(resolver.getResources(MYBATIS_MAPPER));
                bean.setConfigLocation(resolver.getResource(MYBATIS_CONFIG));
                return bean.getObject();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("mapper.xml error: {}",e);
                throw new RuntimeException(e);
            }
        }
        
    }
    
    /**
     * Quartz的配置
     * 
     * @author cjp
     * @date 2016年12月9日
     */
    @Configuration
    public class QuartzConfig {
        
        
        @Bean(name="jobDetail")
        public MethodInvokingJobDetailFactoryBean detailFactoryBean(SyncToAamtyTask task){
            MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
            //是否并发执行
            jobDetail.setConcurrent(false);
            jobDetail.setTargetObject(task);
            jobDetail.setTargetMethod("execute");
            return jobDetail;
        }
    
        @Bean(name = "jobTrigger")
        public CronTriggerFactoryBean cronJobTrigger(MethodInvokingJobDetailFactoryBean jobDetail) {
            CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
            tigger.setJobDetail(jobDetail.getObject());
            try {
                tigger.setCronExpression("0/5 * * * * ? ");// 每5秒执行一次
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return tigger;
    
        }
    
        /**
         * quartz调度工厂
         * 
         * @param cronTriggerBean
         * @return
         */
        @Bean
        public SchedulerFactoryBean schedulerFactory(Trigger cronJobTrigger) {
            SchedulerFactoryBean bean = new SchedulerFactoryBean();
            //用于quartz集群,QuartzScheduler 启动时更新己存在的Job
            bean.setOverwriteExistingJobs(true);
            //用户Quartz集群
    //      bean.setDataSource(dataSource);
            //延时启动,应用启动20秒后
            bean.setStartupDelay(20);
            //注册触发器
            bean.setTriggers(cronJobTrigger);
            return bean;
        }
    }
    
    **
     * @author Hans Westerbeek
     * @author Eddú Meléndez
     */
    public class SpringBootVFS extends VFS {
    
      @Override
      public boolean isValid() {
        return true;
      }
    
      @Override
      protected List<String> list(URL url, String path) throws IOException {
        ClassLoader cl = this.getClass().getClassLoader();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
        Resource[] resources = resolver.getResources("classpath*:" + path + "/**/*.class");
        List<Resource> resources1 = Arrays.asList(resources);
        List<String> resourcePaths = new ArrayList<String>();
        for (Resource resource : resources1) {
          resourcePaths.add(preserveSubpackageName(resource.getURI(), path));
        }
        return resourcePaths;
      }
    
      private static String preserveSubpackageName(final URI uri, final String rootPath) {
        final String uriStr = uri.toString();
        final int start = uriStr.indexOf(rootPath);
        return uriStr.substring(start, uriStr.length());
      }
    
    }
    

    2.SpringBoot整合Mybatis时,会遇到找不到datasource的问题

    原因分析:由于MyBatisMapperScannerConfig加载比较早,而且需要将MyBatisMapperScannerConfig与MybatisConfig分开写。这样才能将dataSource正常注入到SqlSessionFactory里面。

    3.整合Mybatis时打包成jar文件后,error报错,找不到实体类。

    原因分析:由于默认使用的是Mybatis的DefaultVFS进行扫描,需要重新使用SpringBootVFS进行扫描加载,这个可以参考:mybatis-spring-boot-1.1.1
    这样打包后的jar文件就可以正常运行了。

    4.总结

    SpringBoot的使用减少了xml配置,使用Bean更加方便了,而且运行起来更加方便,值得大家使用

    相关文章

      网友评论

          本文标题:Spring Boot整合Mybatis、Quartz项目的经验

          本文链接:https://www.haomeiwen.com/subject/vzyumttx.html