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";
    }

}
相关推荐
想用offer打牌4 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX5 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法6 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte7 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行8 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple8 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东8 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble8 小时前
springboot的核心实现机制原理
java·spring boot·后端