构造函数注入与现场注入 [英] Constructor injection vs Field injection

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

问题描述

在注入任何服务时,我有两种选择:

When injecting any services, I have two choices :

现场注入:

 @Inject 
 private MyService myService;

构造函数注入:

private MyService myService; 

@Inject
public ClassWhereIWantToInject(MyService mySerivce){
    this.myService = myService;
}

为什么构造方法注入优于现场注入

推荐答案

做类似的事情(我假设您正在使用spring-boot或类似的CDI)

Do something like (I assume you are using spring-boot or something comparable for your CDI)

public class ClassWhereIWantToInject{

    private MyService myService; 

    @Inject
    public ClassWhereIWantToInject(MyService mySerivce){
        this.myService = myService;
    }
}

在此相关的问题中有一些有效的论点,为什么使用通过构造函数进行注入而不是通过字段进行注入。归结为,您可以在非CDI环境(即单元测试)中通过构造函数使用初始化,而无需添加更复杂的逻辑。

At this related question there are some valid arguments why to use injection via constructor instead of injection via field. It boils down to the advantage that you can use initialization via constructor also in non-CDI environment i.e. Unit Test, without the need to add more complex logic.

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

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