报错信息:
Error creating bean with name ‘dataSource’ defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Generic.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method ‘dataSource’ threw exception; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
版本号
IDEA 2022.2.5
Maven 3.8.1
SpringBoot 2.6.3
dependencies依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
解决办法:
新增一个配置类,但是我不知道为什么这样就可以了
datasourceConfig的代码
package com.demo.Config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
public class datasourceConfig {
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name="transactionManager")
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
完成