spring使用DataSoure注入參數時報No supported DataSource type found


    平常閱讀源碼什么的沒有目的性,所以很少去看什么源碼,主要是比較繞看起來吃力,所以一般工作只是找個模版模仿一下。

以上廢話,割————————————————————————————————————————————————————————————

    最近照常模仿使用了其它項目里的DataSource用法,代碼如下:

    

 1    @Bean
 2     @Primary
 3     @ConfigurationProperties(prefix = "datasource.from")
 4     public DataSource dataSource(){
 5         return DataSourceBuilder.create().build();
 6     }
 7     
 8     @Autowired
 9     @Qualifier("dataSource")
10     private DataSource dataSource;
11 
12     @Bean(name="sqlSessionFactory")
13     public SqlSessionFactory sqlSessionFactory() throws Exception {
14         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
15         bean.setDataSource(dataSource);
16         bean.setConfigLocation(new ClassPathResource("MybatisConfig.xml"));
17         return bean.getObject();
18     }

    在運行初始化的時候報“No supported DataSource type found”,查找網上資料又說沒有指定數據庫類型的。

    於是,自己在配置中增加了datasource.from.type=oracle,運行還是報一樣的錯。於是,到晚上腦子清醒點時,看了下DataSource初始化時的部分源碼。

    主要的是第三段代碼如下:

1 private static final String[] DATA_SOURCE_TYPE_NAMES = { "org.apache.tomcat.jdbc.pool.DataSource", "com.zaxxer.hikari.HikariDataSource", "org.apache.commons.dbcp.BasicDataSource", "org.apache.commons.dbcp2.BasicDataSource" };
public Class<? extends DataSource> findType(){
    if (this.type != null) {
        return this.type;
    }
    for (String name : DATA_SOURCE_TYPE_NAMES) {
    try {
        return ClassUtils.forName(name, this.classLoader);
    }catch (Exception ex) {}
1  private Class<? extends DataSource> getType() {
2       Class<? extends DataSource> type = findType();
3       if (type != null) {
4         return type;
5       }
6       throw new IllegalStateException("No supported DataSource type found");
7     }
1 public DataSource build() {
2      Class<? extends DataSource> type = getType();
3      DataSource result = (DataSource)BeanUtils.instantiate(type);
4      maybeGetDriverClassName();
5      bind(result);
6      return result;
7    }

    看完上面的代碼就明白為什么報錯了,就是說在創建DataSource沒有找到javax.sql.DataSource的子類,也就是必須要引入DATA_SOURCE_TYPE_NAMES枚舉中涉及類的jar包,另外注意引入對應數據庫JDBC的jar包。

 

以上,Good lucky!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM