最简 Spring MVC + 依赖注入 Demo(SpringBoot)

 

 

分层:Controller ←注入→ Service
 
完整可复制,贴合你学的 @RestController@Service@Autowired

1. 依赖(pom.xml)

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

 

 

2. 启动类

java
 
运行
 
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // 自带@ComponentScan 自动扫描当前包及子包
public class MvcDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MvcDemoApplication.class, args);
    }
}

 

 

3. Service 层(业务层)

java
 
运行
 
 
import org.springframework.stereotype.Service;

@Service // 等价于 @Component,标识业务Bean,被容器管理
public class HelloService {

    public String sayHello(String name){
        return "Hello " + name + " ! 来自Service";
    }
}
 

 

4. Controller 层(接收请求)

java
 
运行
 
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController // @Controller + @ResponseBody,返回JSON
public class HelloController {

    // ✅ 依赖注入:Spring自动把容器里的HelloService注入进来
    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String hello(@RequestParam String name){
        // 直接使用注入好的Service,不需要手动 new HelloService()
        return helloService.sayHello(name);
    }
}

 

 

运行测试

启动项目,浏览器访问:
 
http://localhost:8080/hello?name=小明
 
返回结果:
 
Hello 小明 ! 来自Service

结合你知识点的讲解

  1. @Service:衍生自@Component,类被@ComponentScan扫描 → 注册为 Bean
  2. @RestController:同样是构造型注解,也会注册成 Bean
  3. @Autowired:依赖注入
     
    Spring 容器找到HelloService的 Bean,自动赋值给成员变量
  4. ❗重点:我们代码里没有写 new HelloService(),对象由 Spring 创建、管理

拓展:构造器注入(官方推荐写法,替代字段 @Autowired)

java
 
运行
 
 
@RestController
public class HelloController {

    private final HelloService helloService;

    // 构造器注入,SpringBoot 4.3+ 不需要写@Autowired
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello(@RequestParam String name){
        return helloService.sayHello(name);
    }
}
 

 

关键逻辑链路(串联你全套课程)

启动类@SpringBootApplication
 
→ 开启@ComponentScan扫描
 
→ 识别@Service@RestController,注册两个 BeanDefinition
 
→ 容器实例化 Bean
 
→ 执行依赖注入,把HelloService注入HelloController
 
→ 接收 HTTP 请求,调用 service 方法
posted @ 2026-07-22 20:49  漫漫长路</>  阅读(8)  评论(0)    收藏  举报