如何解决Spring Boot/MVC:考虑在您的配置中定义一个类型为“pack.website.repositories.CustomerRepository”的 bean
在我解释问题之前,我已经经历了导致我面临的错误的类似线程。所以我看了看,没有一个解决方案有帮助,因此,我发布了我自己的自定义问题。创建一个简单的 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);
}
}
解决方法
可能是它无法正确扫描包或者您在 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);
}
}
后面跟着 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 是在控制器中自动装配的),而我刚刚添加了基本包名称,希望它对 @throwawayaccount2020 有所帮助,而如果您使用接口在 Repository 上工作,则使用 @Service 标签必填
@ComponentScan(basePackages = { "com.example.jpalearner" })
数据库
CREATE TABLE studentinformation
(
regid serial NOT NULL,studentname character varying(250) NOT NULL
);
文件树
,使用服务层 @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注解,则会出现以下错误
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。