一般在项目中都会使用springboot,如果需要使用mysql,一般都会使用阿里的druid数据库连接池,那使用这个连接池的时候,一般都会对druid做一些配置,有的人喜欢在yml中直接配置了,但是有些人可能在程序中搞一个配置类:里面的代码类似于这样:
@Configuration
@MapperScan(basePackages = "com.gbgg.graph.goods.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class DuridConfig {
@Value("${spring.datasource.primary.url:#{null}}")
private String dbUrl;
@Value("${spring.datasource.primary.username: #{null}}")
private String username;
@Value("${spring.datasource.primary.password:#{null}}")
private String password;
@Value("${spring.datasource.primary.driverClassName:#{null}}")
private String driverClassName;
@Value("${spring.datasource.initialSize:#{null}}")
private Integer initialSize;
@Value("${spring.datasource.minIdle:#{null}}")
private Integer minIdle;
@Value("${spring.datasource.maxActive:#{null}}")
private Integer maxActive;
@Value("${spring.datasource.maxWait:#{null}}")
private Integer maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis:#{null}}")
private Integer timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis:#{null}}")
private Integer minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery:#{null}}")
private String validationQuery;
@Bean(name = "jdbcTemplate")@Primary
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
但是这样就会有个问题这个配置类中自己new了一个SqlSessionFactoryBean,这就会导致在yml文件中配置的xml路径根本不起作用,也就是说根本找不到xml文件,所以上面的异常就会一直报。那怎么解决呢?
就是在在即new 的这个SqlSessionFactoryBean中,把xml路径给指定了就可以了,那怎么指定呢,看下面代码:
@Bean(name = "sqlSessionFactory")
@Primary
public SqlSessionFactory setSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setCallSettersOnNulls(true);
bean.setConfiguration(configuration);
bean.setVfs(SpringBootVFS.class);
//下面这两个就是指定xml路径的
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
bean.setDataSource(dataSource);
return bean.getObject();
}
这样的话就可以扫描到resource下面的xml文件了,这样的话就可以在在使用注解的情况下也使用xml进行dao层的数据书写了。