我有一个带有静态方法的 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>
最佳答案
我的方法是让希望访问的 bean 实现 InitializingBean
或使用 @PostConstruct
,并包含对其自身的静态引用。
例如:
@Service
public class MyBean implements InitializingBean {
private static MyBean instance;
@Override
public void afterPropertiesSet() throws Exception {
instance = this;
}
public static MyBean get() {
return instance;
}
}
因此,您的静态类中的用法就是:
MyBean myBean = MyBean.get();
这样,不需要 XML 配置,你不需要将 bean 作为构造函数参数传入,调用者不需要知道或关心 bean 是使用 Spring 连接的(即,没有需要凌乱的 ApplicationContext
变量)。
关于java - 以静态方法访问spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12537851/