• Spring实现Bean注入的常见方式


    Spring框架中,依赖注入是一种设计模式,它允许开发者将对象之间的依赖关系由Spring容器来管理,而不需要再代码中硬编码这些依赖关系,降低组件之间的耦合度,提高代码的可维护性和灵活性。

    实现依赖注入的主要方式:

    1.构造函数注入

    通过在类的构造函数中声明需要注入的依赖,Spring容器在创建对象实例时自动注入所需的依赖。

    1. public class MyService {
    2. private final MyRepository myRepository;
    3. public MyService(MyRepository myRepository) {
    4. this.myRepository = myRepository;
    5. }
    6. }

    2.Setter方法注入

    通过类的Setter方法设置依赖对象

    1. public class MyService {
    2. private final MyRepository myRepository;
    3. public MyService(MyRepository myRepository) {
    4. this.myRepository = myRepository;
    5. }
    6. }

    3.字段注入

    直接在字段上使用@Autowired注解进行注入

    1. public class MyService {
    2. @Autowired
    3. private MyRepository myRepository;
    4. }

    4.接口注入

    通过实现接口,并在接口中定义注入方法来实现依赖注入

    1. public interface MyService {
    2. void setMyRepository(MyRepository myRepository);
    3. }
    4. public class MyServiceImpl implements MyService {
    5. private MyRepository myRepository;
    6. @Override
    7. public void setMyRepository(MyRepository myRepository) {
    8. this.myRepository = myRepository;
    9. }
    10. }

    5.通过xml配置文件进行注入

    在 Spring 的 XML 配置文件中使用  元素来声明 Bean,并使用  元素来进行属性注入。

    1. "myService" class="com.example.MyService">
    2. "myRepository" ref="myRepository"/>
    3. "myRepository" class="com.example.MyRepository"/>

    6.通过java配置进行注入

    使用java config类并在其中使用@bean注解来声明bean的注入,并使用@autowired注解进行依赖注入

    1. @Configuration
    2. public class AppConfig {
    3. @Bean
    4. public MyService myService(MyRepository myRepository) {
    5. return new MyService(myRepository);
    6. }
    7. @Bean
    8. public MyRepository myRepository() {
    9. return new MyRepository();
    10. }
    11. }

    在 Spring 中,我们通常使用 @Autowired 注解或者对应 XML 配置文件来实现依赖注入。@Autowired 注解可以用在构造函数、Setter 方法、字段上,告诉 Spring 容器要自动装配这些依赖。同时,你也可以通过 XML 配置文件来定义 bean 的依赖关系。当 Spring 容器启动时会读取这些配置文件,并自动完成依赖注入

  • 相关阅读:
    zero_damaged_pages 隐含参数,处理磁盘页损坏(先占位)
    Golang学习之路4-函数/导入包/命令行参数/defer等
    Kotlin语言内置函数学习2:with,also,takeIf,takeUnless
    VueX/Pinia的优缺点
    springboot
    卡尔曼家族从零解剖-(07) 高斯分布积分为1,高斯分布线性变换依旧为高斯分布,两高斯函数乘积仍为高斯。
    现在性价比高的运动耳机有哪些、性价比最高的蓝牙耳机排行榜
    【附源码】计算机毕业设计JAVA校园绿化管理系统
    Python机器视觉--OpenCV入门--视频的加载,录制
    Springboot中自定义监听器
  • 原文地址:https://blog.csdn.net/qq_34704689/article/details/136457152