创建名为“dataSource”+ Spring Boot + Hibernate 的 bean 时出错

Posted

技术标签:

【中文标题】创建名为“dataSource”+ Spring Boot + Hibernate 的 bean 时出错【英文标题】:Error creating bean with name 'dataSource' + Spring Boot + Hibernate 【发布时间】:2018-01-25 03:28:17 【问题描述】:

我在启动有关如何访问 mysql 数据的 spring 指南时遇到了一些问题(请参阅此链接:https://spring.io/guides/gs/accessing-data-mysql/)。我稍微调整了类,所以我有这个代码:

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0      http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.springframework</groupId>
        <artifactId>gs-mysql-data</artifactId>
        <version>0.1.0</version>
    
        <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    </parent>
    
    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- Use MySQL Connector-J -->
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    </dependencies>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
    </build>
    

我正在使用这个主控制器: MainController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.resource.iPbackend.UserRepository;
import com.resource.iPbackend.User;

@Controller
@RequestMapping(path = "/main")
public class MainController 

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(path = "/reg", method = RequestMethod.POST)
    public @ResponseBody String regNewUser (@RequestParam String firstName,      @RequestParam String lastName, @RequestParam String email, @RequestParam String password, @RequestParam String username) 
        User n = new User();
        n.setFirstName(firstName);
        n.setLastName(lastName);
        n.setEmail(email);
        n.setPassword(password);
        n.setUsername(username);
        userRepository.save(n);
        return "User is stored in database: " + n;
    

    @GetMapping(path = "/all")
    public @ResponseBody Iterable<User> getAllUsers() 
        return userRepository.findAll();
    

连同这个存储库: UserRepository.java

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.resource.iPbackend.User;


@Repository
public interface UserRepository extends CrudRepository<User, Long> 


还有这个实体: User.java

import org.springframework.data.annotation.Id;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class User 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String username;

    public Integer getId() 
        return id;
    

    public void setId(Integer id) 
        this.id = id;
    

    public String getFirstName() 
        return firstName;
    

    public void setFirstName(String firstName) 
        this.firstName = firstName;
    

    public String getLastName() 
        return lastName;
    

    public void setLastName(String lastName) 
        this.lastName = lastName;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    public String getUsername() 
        return username;
    

    public void setUsername(String username) 
        this.username = username;
    

最后我有了这个 Application.class:

@EnableAutoConfiguration
@SpringBootApplication
public class IPbackendApplication 

public static void main(String[] args) 

    SpringApplication.run(IPbackendApplication.class, args);


我收到此错误:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration”的bean时出错:通过构造函数参数0表示的不满足依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class] 中定义名称为“dataSource”的 bean 创建时出错:通过工厂方法进行 Bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.apache.tomcat.jdbc.pool.DataSource]:工厂方法 'dataSource' 抛出异常;嵌套异常是 java.lang.IllegalArgumentException: URL 必须以 'jdbc' 开头 在 org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] 在 org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE] 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]

感谢您的帮助!

【问题讨论】:

缺少相关代码:spring 使用的数据库配置在哪里? 【参考方案1】:

查看异常跟踪中的这条消息:

嵌套异常是 org.springframework.beans.BeanInstantiationException:失败 实例化[org.apache.tomcat.jdbc.pool.DataSource]:工厂方法 'dataSource' 抛出异常;嵌套异常是 java.lang.IllegalArgumentException: URL 必须以 'jdbc' 开头 在 org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)

您很可能没有提供重视spring.datasource.url 属性的application.properties 文件。 否则你没有正确地评估它。

它应该看起来像:

spring.datasource.url=jdbc:mysql://localhost/mydb

您可以参考the Spring Boot documentation。

【讨论】:

【参考方案2】:

您分享的最后一个属性有一些错误需要修复spring.datasource.data-username=myuserspring.datasource.data-password=ThePassword

这是如何正确配置 spring 数据源的示例

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=ThePassword

这是Spring documentation的另一个例子

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

【讨论】:

【参考方案3】:

我在尝试测试我的 dao 层时收到了非常相似的错误。

@RunWith(SpringRunner.class)
@DataJpaTest
public class ItemRepositoryTest 

    @Autowired
    private ItemRepository itemRepository;

    @Test
    public void findAll() 
        List<Item> allItems = itemRepository.findAll();
        Assertions.assertThat(allItems).hasSize(9);
    

问题已通过添加解决:

@AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)

到测试班:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)
public class ItemRepositoryTest ...

【讨论】:

以上是关于创建名为“dataSource”+ Spring Boot + Hibernate 的 bean 时出错的主要内容,如果未能解决你的问题,请参考以下文章

创建在类路径资源[applicationcontext]中定义名为“工厂”的bean时出错。:在设置bean属性“dataSource”时,无法解析对bean“dataSource”的引用;嵌套异常是

对 spring 中默认的 DataSource 创建进行覆盖

如何为 Spring Datasource 创建自定义重试逻辑?

在内存数据库中嵌入 HSQL 的 Spring DataSource 和 Linux 上的休眠创建-删除排序

一个组件需要一个名为“dataSource”的 bean,但找不到该 bean

H2 DB的Spring Boot两个Datasource配置创建表和插入数据失败