繁体   English   中英

Spring 引导/MVC:考虑在配置中定义类型为“pack.website.repositories.CustomerRepository”的 bean

[英]Spring Boot/MVC: Consider defining a bean of type 'pack.website.repositories.CustomerRepository' in your configuration

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

描述:

pack.website.controllers.LandingPageController 中的字段 cRepo 需要找不到类型为“pack.website.repositories.CustomerRepository”的 bean。

注入点有以下注解:

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

行动:

考虑在您的配置中定义类型为“pack.website.repositories.CustomerRepository”的 bean。

在配置我的 Controller class 和回购 class 之后。 下面我将附上代码和我的主要内容。 有谁知道为什么这个错误仍然发生? 我已经尝试过@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);
    }

}

可能是它无法正确扫描 package,或者您在 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);
}

使用实体 class

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 是在控制器中自动装配的),而我刚刚添加了基本 package 名称,希望它对@throwawayaccount2020 有所帮助,而如果您使用接口在 Repository 上工作,则需要 @Service 标签

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

Sql

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

文件树

下列的

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

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 注释,则会出现以下错误

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM