简体   繁体   English

静态类需要使用Spring托管类

[英]Static Class Needs to Use a Spring Managed Class

I have a static initialization block that accesses a class through Spring. 我有一个静态初始化块,可通过Spring访问类。 How can I ensure that the Spring Container is loaded before the static class? 如何确保在静态类之前加载Spring容器?

public class A {
}

public class B {
     static {
          ctx.getBean(A.class); // error if container is not ready
     }
}

Really, it will be a lot easier if B would be also managed by Spring and instead of providing static methods would be injected into classes where it needed. 确实,如果B也由Spring管理,而不是提供静态方法而将B注入需要的类中,将会容易得多。

Now, if you still have to proceed with your approach: You can use static initialization method instead of static block, let say 现在,如果您仍然必须继续使用方法:可以使用静态初始化方法代替静态块,可以说

class B{
   private static A beanA;
   public static void setBeanA(A bean){
      beanA = bean;
   }
}

Now all you need to do is call to make sure this set is called during context creation. 现在,您需要做的就是调用以确保在上下文创建期间调用了该集合。 The simplest way is to create another class, and declare it as a bean, or you can make that set method return something and use it factory method, or autowire an A to it and use some post processing - whatever you like more. 最简单的方法是创建另一个类,并将其声明为Bean,或者您可以使set方法返回某些内容并使用它的工厂方法,或者将A自动装配到它上并使用一些后处理-无论您喜欢什么。 Here is an example with using another bean: 这是使用另一个bean的示例:

public class C{
   public C(A bean){
      B.setBeanA(bean);
   }
}

than in spring config you can have: 比在spring配置中可以有:

<bean name="A" class="A.class"/>
<bean class="C.class">
   <constructor-arg ref="A"/>
</bean>

Note, that instead passing a bean, you can use the same approach to pass the whole applicationContext. 请注意,可以通过相同的方法来传递整个applicationContext,而不是传递Bean。

In general, this is very shaky approach, and it assumes that you Spring context will be up before anything starts happening in the application. 通常,这是一种非常不稳定的方法,它假定您的Spring上下文在应用程序中开始发生任何事情之前就已经启动。

如果类B是带有私有构造函数的静态类,该怎么办?

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

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