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

}
相关推荐
華勳全栈9 分钟前
两天开发完成智能体平台
java·spring·go
程序新视界13 分钟前
为什么不建议基于Multi-Agent来构建Agent工程?
人工智能·后端·agent
alonewolf_9914 分钟前
Spring MVC重点功能底层源码深度解析
java·spring·mvc
Victor35625 分钟前
Hibernate(29)什么是Hibernate的连接池?
后端
Victor35626 分钟前
Hibernate(30)Hibernate的Named Query是什么?
后端
源代码•宸1 小时前
GoLang八股(Go语言基础)
开发语言·后端·golang·map·defer·recover·panic
czlczl200209251 小时前
OAuth 2.0 解析:后端开发者视角的原理与流程讲解
java·spring boot·后端
颜淡慕潇1 小时前
Spring Boot 3.3.x、3.4.x、3.5.x 深度对比与演进分析
java·后端·架构
布列瑟农的星空1 小时前
WebAssembly入门(一)——Emscripten
前端·后端
芒克芒克2 小时前
本地部署SpringBoot项目
java·spring boot·spring