以静态方法访问spring bean [英] Accessing spring beans in static method

查看:314
本文介绍了以静态方法访问spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有静态方法的Util类。在我的Util类中,我想使用spring bean,所以我将它们包含在我的util类中。
据我所知,将spring bean用作静态字段并不是一个好习惯。
但是有没有办法以静态方法访问spring bean?

I have a Util class with static methods. Inside my Util class, I want to use spring beans so I included them in my util class. As far as I know it's not a good practice to use spring beans as static fields. But is there any way to access spring beans in a static method?

我的例子:

public class TestUtils {

   private static TestBean testBean;

   public void setTestBean(TestBean testBean) {
     TestUtils.testBean = testBean;
   }

  public static String getBeanDetails() {
    return beanName = testBean.getDetails();
  }
}

我在很多论坛上看到这不是最佳实践。有人能告诉我如何处理这种情况吗?

I have seen in many forums that this is not a best practice. Can someone show me how I can handle this type of scenario?

我的配置文件:

<bean id="testUtils" class="com.test.TestUtils">
 <property name="testBean" ref="testBean" />
</bean>


推荐答案

我的方法是针对想要访问的bean实现 InitializingBean 或使用 @PostConstruct ,并包含对自身的静态引用。

My approach is for the bean one wishes to access to implement InitializingBean or use @PostConstruct, and containing a static reference to itself.

例如:

@Service
public class MyBean implements InitializingBean {
    private static MyBean instance;

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }

    public static MyBean get() {
        return instance;
    }
}

因此,静态类中的用法只是:

Usage in your static class would therefore just be:

MyBean myBean = MyBean.get();

这样,不需要XML配置,你不需要将bean作为一个传递来构造函数参数,并且调用者不需要知道或关心bean是否使用Spring连接(即,不需要凌乱的 ApplicationContext 变量)。

This way, no XML configuration is required, you don't need to pass the bean in as a constructor argument, and the caller doesn't need to know or care that the bean is wired up using Spring (i.e., no need for messy ApplicationContext variables).

这篇关于以静态方法访问spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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