将一个Bean注入为静态依赖。

huangapple go评论61阅读模式
英文:

Inject a bean as static dependency

问题

将依赖 bean 作为静态变量注入,可能会导致问题吗?

英文:

Inyecting dependency bean as static, could lead to problems?

@Component
public class SomeBean {
    
    @Autowired
    private static DependencyBean dependency;
    ...
}

答案1

得分: 1

Spring、CDI(以及可能还有像Guice等其他框架)通常不允许你将一个Bean注入到一个静态字段中,这是为什么呢?

虽然Spring理论上是可以支持将内容注入到静态字段中的,但如果两个拷贝的Bean都被管理,就会出现冲突,因为静态字段在类的所有实例之间共享。在你的示例中,你只有一个被管理的实例,它在非常狭窄的范围内可以“工作”,但项目通常不会那么简单,这就是为什么Spring不支持这种方式的主要原因:

<!-- 这不是一个真正的Spring定义,只是一个示例 -->
<bean id="example1" class="com.example.SomeBean">
    <property name="dependency" value="dependencyV1"/>
</bean>
<bean id="example2" class="com.example.SomeBean">
    <property name="dependency" value="alternateDependencyV2"/>
</bean>

还有其他原因,涉及到类加载、构造函数以及DI/IOC的整个理念,但这是主要原因。

当然,也有一些方法可以绕过这种限制(不建议使用):https://www.baeldung.com/spring-inject-static-field

英文:

Spring, CDI (and likely others like Guice, etc) don't allow you to "inject" a bean into a static field as a rule. Why would this be?

While Spring certainly could support injecting contents into static fields, conflict would arise if two copies of the bean were managed since static fields are shard among all instances of the class. In your example, you have exactly one managed instance, and it would "work" in that very narrow scope, but projects aren't usually that simplistic, which is why it is not supported by Spring:

&lt;!-- not a real spring definition, just an example --&gt;
&lt;bean id=&quot;example1&quot; class=&quot;com.example.SomeBean&quot;&gt;
    &lt;property name=&quot;dependency&quot; value=&quot;dependencyV1&quot;/&gt;
&lt;/bean&gt;
&lt;bean id=&quot;example2&quot; class=&quot;com.example.SomeBean&quot;&gt;
    &lt;property name=&quot;dependency&quot; value=&quot;alternateDependencyV2&quot;/&gt;
&lt;/bean&gt;

There are other reasons around classloading, constructors, and the whole philosophy of DI/IOC, but that is the main reason.

And there are ways to defeat this protection (not recommended): https://www.baeldung.com/spring-inject-static-field

huangapple
  • 本文由 发表于 2023年6月8日 21:44:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定