安装器注入与构造器注入 [英] Setter Injection vs. Constructor Injection

查看:112
本文介绍了安装器注入与构造器注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在春天3书中,
第4章 - 简介IOC和DI在Spring中 - 第59页,在Setter Injection vs. Constructor Injection部分中,段落说


$包括Spring,提供一种机制,确保在
时使用Setter Injection定义所有依赖关系,但是通过使用Constructor Injection,您可以断言依赖关系的要求一个容器不可知的方式


你可以用例子来解释

解决方案

只有在提供参数的情况下,才能将所需的依赖关系作为构造函数参数进行实例化(您应该有一个guard子句来确保参数不为空)。因此,构造函数会强制执行依赖性要求是否使用Spring,使其与容器无关。



如果使用setter注入,则setter可能被调用也可能不会被调用,所以实例可能永远不会提供d依赖。强制设置者调用的唯一方法是使用 @Required @Autowired
特别是Spring,因此不会与容器无关。



所以为了使您的代码与Spring无关,请使用构造函数参数进行注入。



更新:Spring 4.3将执行在单构造方案中隐式注入,使您的代码更加独立于Spring,可能不需要 @Autowired 注释。


In a Pro Spring 3 Book, Chapter 4 - Introduction IOC and DI in Spring - Page 59, In "Setter Injection vs. Constructor Injection" section, a paragraph says

Spring included, provide a mechanism for ensuring that all dependencies are defined when you use Setter Injection, but by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner"

Could you explain with examples

解决方案

A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.

If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required or @Autowired , which is specific to Spring and is therefore not container-agnostic.

So to keep your code independent of Spring, use constructor arguments for injection.

Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired annotation at all.

这篇关于安装器注入与构造器注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆