【问题标题】:Spring Boot/MVC: Consider defining a bean of type 'pack.website.repositories.CustomerRepository' in your configurationSpring Boot/MVC:考虑在你的配置中定义一个 'pack.website.repositories.CustomerRepository' 类型的 bean
【发布时间】:2021-04-04 15:24:11
【问题描述】:

在我解释问题之前,我已经经历了导致我面临的错误的类似线程。所以我看了看,没有一个解决方案有帮助,因此,我发布了我自己的自定义问题。创建一个简单的 Spring Boot/MVC 项目时出现此错误:

说明:

pack.website.controllers.LandingPageController 中的字段 cRepo 需要 一个 'pack.website.repositories.CustomerRepository' 类型的 bean 找不到。

注入点有如下注解:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

行动:

考虑定义一个 bean 类型 'pack.website.repositories.CustomerRepository' 在你的配置中。

在配置了我的 Controller 类和 repo 类之后。下面我将附上代码和我的主要内容。有谁知道为什么这个错误仍然发生?我已经尝试过@component、@service(在我的服务类中)、@repository 标记......仍然无法正常工作。请帮忙:

@Controller
public class LandingPageController {
    
    @Autowired
    private CustomerRepository cRepo;

    @GetMapping("")
    public String viewLandingPage() {
        return "index";
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("customer", new Customer());
        return "signup_form";
    }

    @PostMapping("/process_register")
    public String processRegister(Customer customer) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(customer.getPassword());
        customer.setPassword(encodedPassword);
        cRepo.save(customer);

        return "register_success";
    }

    @GetMapping("/users")
    public String listUsers(Model model) {
        List<Customer> listUsers = cRepo.findAll();
        model.addAttribute("listUsers", listUsers);

        return "users";
    }

}

#############

public interface CustomerRepository extends JpaRepository<Customer, Long>{
    
    public Customer findByEmail(String email);

}

#############

public class CustomerService implements UserDetailsService {

    @Autowired
    private CustomerRepository cRepo;

    @Override
    public CustomerDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = cRepo.findByEmail(username);
        if (customer == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new CustomerDetails(customer);
    }

}

###########

@SpringBootApplication
@ComponentScan({"pack.website.controllers", "pack.website.repositories" })
public class ProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProjectApplication.class, args);
    }

}

【问题讨论】:

  • 能否在“CustomerRepository”声明前加上“@Repository”再试一次?
  • @AndresSacco 我也试过了。
  • 查看您在“ProjectApplication”中扫描的包。您只扫描控制器和存储库而不扫描服务,尝试扫描“pack.website”并在“CustomerService”中添加服务标签。同时在 CustomerRepository 中添加“repository”标签
  • @AndresSacco 我试了一下。同样的错误。现在,当我将 @ComponentScan({"pack.website.controllers.LandingPageController", "pack.website.repositories.CustomerRepository" }) 添加到我的主目录时。它可以构建,但显示的是 spring security 的默认登录而不是我的自定义 Index.html。我已经尝试禁用弹簧安全性....但这没有用。
  • 尝试去掉componentScan注解,在如下注解中添加要扫描的路径:@SpringBootApplication(scanBasePackages = {"pack.website"}),当然别忘了用注释@Repository。

标签: java spring spring-boot spring-mvc spring-data-jpa


【解决方案1】:

使用服务层 @Service 注释可能有助于以下是控制器部分

package com.example.jpalearner.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.jpalearner.jpa.JpaService;
import com.example.jpalearner.jpa.Studentinformation;
import com.example.jpalearner.service.StudentInfoService;
@RestController
public class RouterController {
    
    @Autowired
    StudentInfoService service;
    
    @PostMapping(value = "/searchByservice")
    public Studentinformation  searchByservice(@RequestBody Studentinformation studentinformation)
    {
        try {
            return service.fetchByName(studentinformation);
        } catch (Exception e) {
            System.err.println(e);
        }
        return null;

    }
    
}

服务接口

package com.example.jpalearner.service;

import com.example.jpalearner.jpa.Studentinformation;

public interface StudentInfoService {
    public Studentinformation fetchByName(Studentinformation obj);
}

以及实现

package com.example.jpalearner.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.jpalearner.jpa.JpaService;
import com.example.jpalearner.jpa.Studentinformation;
import com.example.jpalearner.service.StudentInfoService;
@Service
public class StudentInfoServiceImpl implements StudentInfoService {
    @Autowired
    private JpaService repos;
    @Override
    public Studentinformation fetchByName(Studentinformation obj) {
        // TODO Auto-generated method stub
        return repos.findByStudentname(obj.getStudentname());
    }

}

如果我错过了@Service 注释,则会出现以下错误

【讨论】:

    【解决方案2】:

    可能是它无法正确扫描包,或者您在 CustomerService.java 中缺少 @service 标签,同时检查以下代码是否有用,以下是 ServletInitializer

    package com.example.jpalearner;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan(basePackages = { "com.example.jpalearner" })
    @SpringBootApplication
    public class ServletInitializer extends SpringBootServletInitializer {
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(ServletInitializer.class);
        }
    
    }
    

    后跟路由器控制器

    package com.example.jpalearner.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.example.jpalearner.jpa.JpaService;
    import com.example.jpalearner.jpa.Studentinformation;
    @RestController
    public class RouterController {
        @Autowired
        private JpaService repos;
        
        
        @GetMapping
        public String defaultpath()
        {
            return "Hello World";
        }
        
        @PutMapping(value = "/save")
        public Map<String, Object> SaveRecord(@RequestBody Studentinformation studentinformation) {
            Map<String, Object> res = new HashMap<String, Object>();
    
            try {
                repos.save(studentinformation);
                res.put("saved", true);
            } catch (Exception e) {
                res.put("Error", e);
            }
            return res;
    
        }
        
        @PostMapping(value = "/search")
        public Studentinformation  GetRecord(@RequestBody Studentinformation studentinformation)
        {
            try {
                return repos.findByStudentname(studentinformation.getStudentname());
            } catch (Exception e) {
                System.err.println(e);
            }
            return null;
    
        }
    }
    

    实现 JPA 的接口

    package com.example.jpalearner;
    
    import org.springframework.data.repository.CrudRepository;
    
    public interface JpaService extends CrudRepository<Studentinformation, Long> {
    
        public Studentinformation findByStudentname(String email);
    }
    

    使用实体类

    package com.example.jpalearner.jpa;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Studentinformation {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long regid;
        
        public Long getRegid() {
            return regid;
        }
    
        public void setRegid(Long regid) {
            this.regid = regid;
        }
        
        private String studentname;
    
        public String getStudentname() {
            return studentname;
        }
    
        public void setStudentname(String studentname) {
            this.studentname = studentname;
        }
    
    
    }
    

    应用属性如下

    ## default connection pool
    spring.datasource.hikari.connectionTimeout=20000
    spring.datasource.hikari.maximumPoolSize=5
    
    ## PostgreSQL
    spring.datasource.url=jdbc:postgresql://localhost:5432/testjpa
    spring.datasource.username=postgres
    spring.datasource.password=xyz@123
    

    下面是pom

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.1</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example.jpalearner</groupId>
        <artifactId>simplejpalearner</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <name>simplejpasample</name>
        <description>Demo project for Spring Boot, and jpa test</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </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-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web-services</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    我没有使用 @Service 或 @Repository 标签(因为 repo 是在控制器中自动装配的),而我刚刚添加了基本包名称,希望它对 @throwawayaccount2020 有所帮助,而如果您使用接口在 Repository 上工作,那么 @Service 标签是必需的

    @ComponentScan(basePackages = { "com.example.jpalearner" })
    

    SQL

    CREATE TABLE studentinformation
    (
      regid serial NOT NULL,
      studentname character varying(250) NOT NULL
    );
    

    文件树

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2022-09-29
      • 2018-06-22
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2020-08-01
      • 2019-02-14
      • 2018-12-21
      相关资源
      最近更新 更多