请求 Spring 控制器 returns 404 未找到

Request to Spring Controller returns 404 not found

我正在尝试设置一个 Spring MVC 应用程序,但每次我从邮递员调用 http://localhost:9001/tasks API 时,我都会收到以下错误:

这是我的代码:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class TaskManagerApplication {

public static void main(String[] args) {
    SpringApplication.run(TaskManagerApplication.class, args);
}


@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:4200");
        }
    };
}
}

任务库:

@Path("tasks")
@ApiIgnore
@Component
@AllArgsConstructor
public class TaskResource {

private final TaskService taskService;

@GET
@Produces(APPLICATION_JSON)
public List<Task> getAllTasks() {
    return taskService.getTasks();
}

任务服务:

@Service
@RequiredArgsConstructor
public class TaskService {

private final TaskRepository taskRepository;

public List<Task> getTasks() {
    return taskRepository.findAll();
}

项目结构:

您正在 spring 引导中使用 JAX-RS。 Spring 以自己的方式处理 rest,如果你想使用 JAX-RS 而不是 Springs Rest Annotations,你需要做一些额外的配置。

首先,您需要在 build.gradlepom.xml 文件中添加 JAX-RS 依赖项。我想你已经这样做了。 Jersey 是 JAX-RS 实现之一,如果要添加它,则需要执行以下操作。
build.gradle

implementation "org.springframework.boot:spring-boot-starter-jersey"

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

之后,您需要使用 Spring 注册 JAX-RS 个端点。我想你错过了这一步。

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JaxrsConfig extends ResourceConfig {

    public JaxrsConfig() {
        register(TaskResource.class);
    }
}

在此之后,您的 JAX-RS 端点将注册到 spring。

但如果您使用 spring,我会建议您遵循 spring 注释。如果您使用 spring 注释,您的代码将如下所示。

@RestController
@RequestMapping(path = "tasks")
public class TaskResource {

    @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<String> getAllTasks() {
        return Arrays.asList("a","b");
    }
}

此外,您还需要从 spring 中删除 JAX-RS 才能使用此 Spring MVC 注释。