使用JAVA代码来整合spring和mybatis配置文件

非常讨厌使用xml配置spring和mybati的配置文件.故尝试使用JAVA代码来编写spring和mybati的整合配置文件
很开心搭建成功,JAVA配置代码如下

package com.spring.study;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
@Configuration  //标明为spring的配置类
@ComponentScan  //开启spring的自动扫描bean和管理bean
@MapperScan("com.spring.study.dao")//开启mybatis的自动扫描mapper接口和管理
public class SpringConfig {

    //数据源
    @Bean
    public PooledDataSource dataSource() {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.168.0.23:3306/lalala?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("shanhao");
        dataSource.setPassword("23232322");
        return dataSource;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource());
        FileSystemResource fileSystemResource = new FileSystemResource("C:\\mapping\\InstrumentMapper.xml");
        sqlSessionFactory.setMapperLocations(new Resource[]{fileSystemResource});
        return sqlSessionFactory;
    }
}

Resource我用的是绝对路径的,一般可以用相对路径的Resource比较好一点,我懒得改,开发的时候注意一下
把FileSystemResource 换成解析相对路径的类就好了,有空我找下重新贴下

以防万一,顺便贴上目录,防止有些童鞋迷失
目录

猜你喜欢

转载自www.cnblogs.com/123-LLL/p/9171084.html