Spring依赖注入的三种方式

1、 settter方法注入 以@Autowired注解为例,即把@Autowired注解标记在目标bean的引用bean的setter方法上。

kotlin 复制代码
@RestController
@RequestMapping("/abc")
public class AbcController {


    private AbcService abcService;

    @Autowired
    public void setAbcService(AbcService abcService) {
        this.abcService = abcService;
    }

    @GetMapping("/rateLimit")
    public  String  rateLimit(){

        System.out.println("start");
        abcService.printABC();
        return "abc";
    }

}

2.构造器注入

kotlin 复制代码
@RestController
@RequestMapping("/abc")
public class AbcController {


    private AbcService abcService;
    
    public AbcController(AbcService abcService) {
        this.abcService = abcService;
    }

    @GetMapping("/rateLimit")
    public  String  rateLimit(){

        System.out.println("start");
        abcService.printABC();
        return "abc";
    }

}

3.变量(filed) 注入

kotlin 复制代码
@RestController
@RequestMapping("/abc")
public class AbcController {

    @Autowired
    private AbcService abcService;
    

    @GetMapping("/rateLimit")
    public  String  rateLimit(){

        System.out.println("start");
        abcService.printABC();
        return "abc";
    }

}
相关推荐
IT_陈寒14 小时前
Java中equals方法比了个寂寞?原来这才是正确的重写姿势
前端·人工智能·后端
Thneonl14 小时前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
卷福同学14 小时前
第一次当面试官有感
后端·面试
苏三说技术14 小时前
为什么越来越多人用 OnlyOffice?
后端
知守观14 小时前
@Transactional 事务失效排查,try-catch 吞异常导致回滚失败(附源码分析)
后端·spring
羑悻14 小时前
Codex + Seed-2.1-pro 实测:多模态理解 + Coding Agent 能扛住真实仓库吗?
后端
颜进强14 小时前
14 · NestJS ExecutionContext 执行上下文:守卫、拦截器、过滤器拿到的"同一个 context",为什么能力不一样?
前端·后端·ai编程
小小张说故事14 小时前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python
明月_清风14 小时前
数据进入平台后怎么处理?一文搞懂 ETL
大数据·后端·数据分析
初学AI的小高14 小时前
LangGraph断点恢复与幂等执行实战
后端·架构