REST API 在带有 H2 数据库的 Spring Boot Maven 多模块项目中总是抛出 404 错误

Posted

技术标签:

【中文标题】REST API 在带有 H2 数据库的 Spring Boot Maven 多模块项目中总是抛出 404 错误【英文标题】:REST API is always throwing 404 error in Spring boot maven multimodule project with H2 database 【发布时间】:2021-05-24 13:17:18 【问题描述】:

我是 Spring Boot 的新手,我用 Spring Boot 创建了一个多模块项目(maven)。我创建了一些 REST API 并连接到 H2 数据库。 数据库连接成功,可以在本地运行。

这是我的项目树。用户管理是父和核心,serverAPI 是子模块。我为每个模块创建了包并添加了相关的类。

我已经尝试了我所知道的一切,并在谷歌上搜索了 5 天,但对我没有任何帮助。我已经包含了我在这里写的每一个代码。请帮我找出问题所在。 (我用的是intellij idea 2020.3 Ultimate)

用户.java

package com.hms.usermanagement.core.model;
import javax.persistence.*;

@Entity
@Table(name = "users")
public class User 

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(name = "full_name")
private String fullName;

@Column(name = "email")
private String email;

public User() 


public User(long id, String fullName, String email) 
    this.id = id;
    this.fullName = fullName;
    this.email = email;


public long getId() 
    return id;


public void setId(long id) 
    this.id = id;


public String getFullName() 
    return fullName;


public void setFullName(String fullName) 
    this.fullName = fullName;


public String getEmail() 
    return email;


public void setEmail(String email) 
    this.email = email;

用户存储库

package com.hms.usermanagement.core.repository;

import com.hms.usermanagement.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User,Long> 
  

应用程序

package com.hms.usermanagement.serverAPI.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application 
    public static void main(String[] args)
        SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.run(args);

用户控制器

package con.hms.usermanagement.serverAPI.controller;


import com.hms.usermanagement.core.model.User;
import com.hms.usermanagement.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class UserController 

@Autowired
private UserRepository userRepository;

//Create Users
@PostMapping("/user")
public User createUser( @Validated @RequestBody User user)
    return userRepository.save(user);


//View all Users
@GetMapping("/users")
public List<User> getAllUsers()
    return userRepository.findAll();


//Update Users
@PutMapping("/users/id")
public ResponseEntity <User> updateUser(@PathVariable(value = "id") long userId , @RequestBody User userDetails)
    Optional<User> user = userRepository.findById(userId);
    if(user.isPresent())
        User _user = user.get();
        _user.setFullName(userDetails.getFullName());
        _user.setEmail(userDetails.getEmail());
        return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
    else 
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    


//Delete Users
@DeleteMapping("/users/id")
public ResponseEntity<?> deleteUser(@PathVariable(value = "id") long userId)
    userRepository.findById(userId);
    userRepository.deleteById(userId);
    return ResponseEntity.ok().build();

application.properties

spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

#enable H2 console
spring.h2.console.enabled=true

#custom H2 console
spring.h2.console.path=/h2

schema-h2.sql

CREATE TABLE users (id long PRIMARY KEY AUTO_INCREMENT, full_name VARCHAR(30), email VARCHAR(50));

这两个网址我都试过了

即使“id”字段是自动生成的,但我也尝试使用邮递员添加 id.. 但仍然遇到相同的错误

【问题讨论】:

看看这个:springboottutorial.com/spring-boot-and-component-scan 也试过了 你能用最新的代码改进你的问题还是在这里添加? 为什么你的项目被分成两部分?这样一来,它们就是完全不同的 Spring Boot 应用程序。 @KavithaKarunakaran 当然谢谢。我也会试试这个。 :) 【参考方案1】:

你的Sprint boot runner类,Application类在com.hms.usermanagement.serverAPI.application包下,所以Spring boot只会扫描com.hms.usermanagement.serverAPI.application下的组件。因此 Spring boot 无法识别您的核心和 Web 组件。

要解决此问题,请尝试将 Application.java 类移动到 com.hms.usermanagement 下。

或者您可以通过在Application.java类中添加@ComponentScan注解来自定义组件扫描:

@SpringBootApplication
@ComponentScan(basePackages = "com.hms.usermanagement")

【讨论】:

我将它创建为多模块项目。如果我将其删除,则将文件更改为我认为不会是多模块项目的位置 没问题,你只需要在同一个项目位置重命名包即可。 Spring boot 在运行时分析类路径,所有的项目模块都将聚集在同一个 Jar 文件中。 我试过@ComponentScan。但仍然得到相同的结果 尝试其他解决方案,它肯定会工作。在同一个项目 serverAPI 中,将包 com.hms.usermanagement.serverAPI.application 重命名为 com.hms.usermanagement。 我也试试【参考方案2】:

删除@Validated 并尝试@Valid 如下

使用 [LOCALHOST]:[PORT]/api/user 调用

//Create Users
@PostMapping("/user")
public User createUser(@RequestBody @Valid User user)
    return userRepository.save(user);

【讨论】:

我也试过了。但是当我尝试添加 @Valid 时出现错误 -> 无法解析符号 'Valid' 添加以下依赖! javax.validationvalidation-api 没有。所有请求都给出 404。我已经有了那个依赖 嘿,如果可能,请在运行时使用服务器日志和 pom.xml 编辑您的问题。【参考方案3】:

我做了一个新的 maven:mvn clean verify 的项目,问题就解决了。

【讨论】:

以上是关于REST API 在带有 H2 数据库的 Spring Boot Maven 多模块项目中总是抛出 404 错误的主要内容,如果未能解决你的问题,请参考以下文章