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
相关产品推荐
相关产品推荐

