繁体   English   中英

以静态方法访问spring bean

[英]Accessing spring beans in static method

我有一个带有静态方法的 Util 类。 在我的 Util 类中,我想使用 spring bean,所以我将它们包含在我的 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变量)。

静态方法的结果应该只取决于传递给方法的参数,因此不需要调用任何 bean。

如果您需要调用另一个 bean,那么您的方法应该是一个独立 bean 的成员方法。

其他答案为您提供了可行的解决方案,但可以完成的事实并不意味着应该完成。

您还可以实现ApplicationContextAware接口,如下所示:

@Component
public class TestUtils implements ApplicationContextAware {

  private static ApplicationContext ac;

  public static String getBeanDetails() {
    return beanName = ((TestBean) ac.getBean("testBean")).getDetails();
  }

  @Override
  public void setApplicationContext(ApplicationContext ac) {
    TestUtils.ac = ac;
  }

}

这对我有用。

使用 xml 配置(老派)定义您的 bean:

<bean id="someBean1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"><value>${db.driver}</value></property>     
    <property name="url"><value>${db.url}</value></property>
    <property name="username"><value>${db.username_seg}</value></property>
    <property name="password"><value>${db.password_seg}</value></property>
</bean> 

或者用java而不是xml定义它(新学校

@Bean(name = "someBean2")
public MySpringComponent loadSomeSpringComponent() {

  MySpringComponent bean = new MySpringComponent();
  bean.setSomeProperty("1.0.2");
  return bean;
}

静态方法访问spring bean

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

public class TestUtils {

  public static void getBeansFromSpringContext() {
    WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    //for spring boot apps
    //ApplicationContext context = SpringApplication.run(Application.class, args)
    DataSource datasource  = (DataSource)context.getBean("someBean1");
    MySpringComponent springBean  = (MySpringComponent)context.getBean("someBean2");
  }
}   

HTH

类似于@nullPainter 的响应,但我们做了以下工作。 不需要构建后逻辑。 它只是在注入期间直接设置静态成员(在@Autowired 方法中)。

@Service
public class MyUtil {

    private static MyManager myManager;

    @Autowired(required = true)
    public void setMyManager(MyManager manager) {
        myManager = manager;
    }

    public static MyManager getMyManager() {
        return myManager;
    }
}

通用解决方案

您可以创建一个允许从静态上下文访问任何 Bean 的类。 此处的大多数其他答案仅显示如何静态访问单个类。

添加了下面代码中的代理,以防有人在自动装配 ApplicationContext 之前调用 getBean() 方法(因为这会导致空指针)。 此处发布的其他解决方案均未处理该空指针。

我博客的详细信息: https : //tomcools.be/post/apr-2020-static-spring-bean/

用法

UserRepository userRepo = StaticContextAccessor.getBean(UserRespository.class)

StaticContextAccessor 的完整代码:

@Component
public class StaticContextAccessor {

    private static final Map<Class, DynamicInvocationhandler> classHandlers = new HashMap<>();
    private static ApplicationContext context;

    @Autowired
    public StaticContextAccessor(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (context == null) {
            return getProxy(clazz);
        }
        return context.getBean(clazz);
    }

    private static <T> T getProxy(Class<T> clazz) {
        DynamicInvocationhandler<T> invocationhandler = new DynamicInvocationhandler<>();
        classHandlers.put(clazz, invocationhandler);
        return (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz},
                invocationhandler
        );
    }

    //Use the context to get the actual beans and feed them to the invocationhandlers
    @PostConstruct
    private void init() {
        classHandlers.forEach((clazz, invocationHandler) -> {
            Object bean = context.getBean(clazz);
            invocationHandler.setActualBean(bean);
        });
    }

    static class DynamicInvocationhandler<T> implements InvocationHandler {

        private T actualBean;

        public void setActualBean(T actualBean) {
            this.actualBean = actualBean;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (actualBean == null) {
                throw new RuntimeException("Not initialized yet! :(");
            }
            return method.invoke(actualBean, args);
        }
    }
}

这就是我从 spring 注入静态场的方式。

<bean id="..." class="...">
 <property name="fieldToBeInjected">
            <util:constant static-field="CONSTANT_FIELD" />
        </property>
</bean>

也许这也会对你有所帮助。

您概述的方法是我所看到的用于将 Spring bean 注入实用程序类的方法。

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

另一种选择是:

<bean name="methodInvokingFactoryBean" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="TestUtils.setInstance"/>
        <property name="arguments">
            <list>
                <ref bean="testBean"/>
            </list>
       </property>
</bean>

和:

public class TestUtils {

   private static testBean;

   public static void setInstance(TestBean anInstance) {
     testBean = anInstance;
   }

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

更多细节在这里这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM