英文:
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:
<!-- not a real spring definition, just an example -->
<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>
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论