【问题标题】:Application Failed to Start Spring Tool Suite应用程序启动 Spring Tool Suite 失败
【发布时间】:2022-01-21 13:17:40
【问题描述】:

我正在从头开始创建一个 Spring Boot 项目并尝试运行我的项目,但它无法启动。我收到以下错误:

    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    
    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Field users in com.example.demo.DataInitializer required a bean of type 'com.example.repository.UserDao' that could not be found.
    
    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)
    
    Action:
    
    Consider defining a bean of type 'com.example.repository.UserDao' in your configuration.

这是我的 UserDao(存储库):

package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.model.User;

@Repository
public interface UserDao extends JpaRepository<User, Long>{
    User findByEmail(String email);
    User findByStatus(int status);
}

这是我正在尝试运行的我的 DataInitializer 文件:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.example.model.User;
import com.example.repository.UserDao;

@Component
public class DataInitializer implements CommandLineRunner{

    @Autowired
    UserDao users;
    @Autowired
    private PasswordEncoder passwordEncode;
    @Override
    public void run(String... args) throws Exception {
        //System.out.println("Running spring boot demo application");
        this.users.save(User.builder().email("example@gmail.com").phone("1234567890")
                .username("Example Name").userid(10001L).build());
    }
}

【问题讨论】:

  • 1. Structuring your code(Spring boot 应用程序应该在根包中)2.不需要(但可能可以容忍)JpaRepository 上的@Repository 注释。(ref
  • 好的。让我先试试吧。

标签: spring-boot spring-data-jpa hibernate-mapping


【解决方案1】:

您要么必须在演示包(应用程序类)中使用@ComponentScan,要么从演示中创建包,例如:

example.demo.package1
example.demo.package2

代替:

example.package1

(右键单击演示包并从中创建包)

如果您想使用组件扫描并保留您的包名,请参阅https://www.baeldung.com/spring-component-scanning

如果您已经将包和类放在一个地方,您只需将它们拖到正确的包并重构它,因为它可以让您自动更改名称。

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2012-09-08
    • 2017-10-07
    • 2015-10-14
    • 2017-05-12
    • 2019-02-02
    相关资源
    最近更新 更多