开发者

Static Class Needs to Use a Spring Managed Class

I have a static initialization block that accesses a class through Spring. How can I ensure that the Spring Container is loaded before the static class?

public class A {
}

public class B {
     static {
          ctx.getBean开发者_运维技巧(A.class); // error if container is not ready
     }
}


Why don't you initialize the bean B using Spring?


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.

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. Here is an example with using another bean:

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

than in spring config you can have:

<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.

In general, this is very shaky approach, and it assumes that you Spring context will be up before anything starts happening in the application.


What do you do if class B is a static class with a private constructor?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜