Spring 基于注解的三种注入方式

大家都知道,Spring使用最多的就是IOC(控制反转),我们通过将注册Bean,把Bean交由Spring的IOC容器管理,将对象的依赖关系由Spring控制,避免硬编码所造成的过度程序耦合。
其中注解方式的注入Bean,有三种方式:

  1. 使用字段Field注入(使用注解);
  2. 使用Setter方法注入(需要加注解@Autowired等,或者自己创建Bean,调用该Setter方法设进去);
  3. 构造器注入 (需要加注解@Autowired等,或自己创建Bean,放入构造器中创建);

其中Setter注入方式 是Spring 3.x推荐的,
构造器注入方式是Spring 4.x及以上推荐的

不推荐是用字段(Field)注入方式,因为可能会产生NPE问题,还有在编译期无法检查出循环依赖。

而Setter注入方式,单例模式下可以解决循环依赖问题。

而最后的构造器注入,在Spring启动进行bean初始化时自动帮我们检查Null空值, 并且检查出循环依赖,会立马报错,防止在运行时出现错误。依赖关系在构造时由容器一次性设定,组件被创建之后一直处于相对“不变”的稳定状态。
如以下代码会在bean初始化时报错,并指出循环依赖异常:

AService类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by martin on 2018/6/24.
 */
@Service
public class AService {

    private BService bService;

    @Autowired
    public AService(BService bService) {
        this.bService = bService;
    }
}

BService类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by martin on 2018/6/24.
 */
@Service
public class BService {

    private AService aService;

    @Autowired
    public BService(AService aService) {
        this.aService = aService;
    }
}

报错信息:

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  AService defined in file [/Users/martin/Documents/****/****/target/classes/com/****/****/service/AService.class]
↑     ↓
|  BService defined in file [/Users/martin/Documents/****/****/target/classes/com/****/****/service/BService.class]
└─────┘

浅谈spring为什么推荐使用构造器注入

深刻剖析spring三种注入方式以及使用注解的原理

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,554评论 19 139
  • 1.1 spring IoC容器和beans的简介 Spring 框架的最核心基础的功能是IoC(控制反转)容器,...
    simoscode阅读 6,851评论 2 22
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,272评论 6 342
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 4,492评论 2 7
  • 我什么也不会。 读书不会读,职高毕业以后找不到什么好工作,在父母新开的手机店帮忙。开在一个小镇子——镇子中的镇子,...
    茫茫茫茫茫茫阅读 214评论 0 0

友情链接更多精彩内容