为什么Spring不支持直接字段依赖注入(自动连线除外)? [英] Why doesn't Spring support direct field dependency injection (except for autowired)?

查看:217
本文介绍了为什么Spring不支持直接字段依赖注入(自动连线除外)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对直接字段依赖注入感兴趣。传统上,Spring支持构造函数注入(为构造函数提供参数)和基于setter的注入(调用调用setter)。



但是,Spring还可以直接使用注释(没有setter方法的对象的成员字段),通过使用 @Autowired 注释字段来证明。自动装配仅限于beans,因此原始值不能被注入(虽然这可以通过创建类java.lang.String的bean有所规避 - 但是具有自动装配的正常注意事项。)除了这样,Spring支持 @Value 直接从属性等设置成员字段的值。



然而,Spring不允许属性直接设置为成员字段(无自动连线)。



我的问题是:为什么?



显然有这样做,为什么不这样呢?是否有任何大的负面的副作用阻止这一点?还是能力有限,所以只有自动布线才有意义?需要一些比调用setter更大的黑客吗?



请注意,我不想讨论一般的setter和getter的相对优点,只是Spring的原因

解决方案

@Autowired注释使用反射来使私有字段可访问(请参阅这个相关问题)。我可以看到为什么在Spring配置文件中没有使用三个东西。


  1. 由于配置是由bean属性(getter和setter)发生的不能真正地告诉 - 在可能的情况下,两者都存在 - 如果你想例如调用setValue或设置成员值。

  2. 它打破封装。您的Spring配置没有理由了解私有成员变量。有一个注释是确定的,因为它已经在源代码中。

  3. 安全问题。更严格的安全管理员可能不允许通过反思使私人字段可访问。


I am interested in direct field dependency injection. Traditionally, Spring supports both constructor injection (supplying arguments to constructors) and setter-based injection (calling setters on a call).

However, Spring is also capable of direct field injection (setting member fields of an object without a setter method), as evidenced by annotating fields with @Autowired. Autowiring is limited to just "beans", so primitive values cannot be injected (although this can somewhat be circumvented by creating beans of class "java.lang.String" - this works, but has the normal caveats of autowiring.) In addition to this, Spring supports @Value to directly set values to member fields from properties etc.

Yet, Spring does not allow properties to be directly set to member fields (without autowiring).

My question is: why?

It is obviously capable of doing so, so why doesn't it? Are there any big negative side-effects that prevent this? Or is the capability somehow limited so that only autowiring makes sense? Does it need some bigger hacks than calling setters?

Note that I do not wish to discuss the relative merits of having setters and getters in general, just the reasons why Spring has made this choice.

解决方案

The @Autowired annotation uses reflection to make private fields accessible (see this related question). I can see three things why it isn't used in Spring configuration files.

  1. Since configuration happens by bean properties (getters and setters) you can't really tell - in the likely case that both exist - if you want to e.g. call setValue or set the member value.
  2. It breaks encapsulation. Your Spring configuration has no reason to know about private member variables. With an annotation that's ok since it is already right there in the source code.
  3. Security concerns. A more restrictive security manager might not allow making private fields accessible via reflection.

这篇关于为什么Spring不支持直接字段依赖注入(自动连线除外)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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