【发布时间】: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