当前位置: 首页 > 知识库问答 >
问题:

Spring Boot/MVC:考虑定义“pack”类型的bean。网站存储库。配置中的CustomerRepository

娄建义
2023-03-14

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

说明:

包装中的现场cRepo。网站控制器。LandingPageController需要“pack”类型的bean。网站存储库。找不到CustomerRepository“”。

注入点具有以下注释:

  • @组织。springframework。豆。工厂注释。自动连线(必需=真)

措施:

考虑定义“pack”类型的bean。网站存储库。配置中的CustomerRepository。

配置我的Controller类和repo类后。下面我将附加代码和我的main。有人知道为什么这个错误仍然发生吗?我已经尝试了@组件、@服务(在我的服务类中)、@存储库标签......仍然不起作用。请帮助:

@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);
    }

}

共有2个答案

缪兴腾
2023-03-14

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

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());
    }

}

如果我错过了@服务注释,那么将发生以下错误

糜鸿风
2023-03-14

可能是无法正确扫描包,或者CustomerService中缺少@service标记。java,检查以下代码是否有用,下面是Servletializer

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);
    }

}

其次是RouterController

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

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

sql

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

文件树

 类似资料: