【发布时间】:2012-09-14 07:24:08
【问题描述】:
我有一个带有静态方法的 Util 类。在我的 Util 类中,我想使用 spring beans,所以我将它们包含在我的 util 类中。 据我所知,将 spring bean 用作静态字段并不是一个好习惯。 但是有什么方法可以在静态方法中访问 spring bean 吗?
我的例子:
public class TestUtils {
private static TestBean testBean;
public void setTestBean(TestBean testBean) {
TestUtils.testBean = testBean;
}
public static String getBeanDetails() {
return beanName = testBean.getDetails();
}
}
我在许多论坛上看到这不是最佳做法。有人可以告诉我如何处理这种情况吗?
我的配置文件:
<bean id="testUtils" class="com.test.TestUtils">
<property name="testBean" ref="testBean" />
</bean>
【问题讨论】:
-
为什么将spring bean用作静态字段不是一个好习惯?
-
@user59290:因为静态字段不受 Spring 的控制,它们受类加载器的约束。 spring 不能像管理对象那样拆除类。