You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何通过@Autowired/@Inject注入访问另一个RestController的路径

Spring Boot 对等J2EE JAX-RS需求实现方案

需求:实现请求路径 localhost:8080/first/second/get-this,访问后控制台输出 Here You Go!,逻辑完全对齐原J2EE实现。

前置依赖

确保项目pom.xml中已引入Spring Web starter依赖:

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

代码实现

1. FirstController 对应原FirstResource

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;

@RestController
@RequestMapping("/first")
@RequestScope
public class FirstController {

    @Autowired
    private SecondController secondController;

    @RequestMapping("/second")
    public SecondController getSecondController() {
        return secondController;
    }
}

2. SecondController 对应原SecondResource

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class SecondController {

    @GetMapping("/get-this")
    public void getThisMessage() {
        System.out.println("Here You Go!");
    }
}

验证方式

  • 启动Spring Boot项目后,访问http://localhost:8080/first/second/get-this
  • 项目控制台直接打印输出Here You Go!,和原J2EE实现效果完全一致

注解映射说明

  • JAX-RS的@Path注解对应Spring Web的@RequestMapping/@GetMapping等路径绑定注解
  • JAX-RS的@RequestScoped注解对应Spring的@RequestScope请求作用域注解
  • JAX-RS的@Inject注解对应Spring的@Autowired依赖注入注解
  • JAX-RS的@Consumes/@Produces注解对应Spring请求映射注解中的consumes/produces属性

内容的提问来源于stack exchange,提问作者Mixon Tandukar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:27:00