Spring静态初始化bean
嘿, 在 Spring 中应该如何处理静态初始化?我的意思是,我的 bean 有一个静态初始化
private static final Map<String, String> exceptionMapping = ErrorExceptionMapping.getExceptionMapping();
,我需要注意 ErrorExceptionMapping 之前已加载。我尝试了这个:
<bean id="errorExceptionMapping" class="cz.instance.transl.util.ErrorExceptionMapping" />
<bean id="validateService" class="cz.instance.transl.services.ValidateService" depends-on="errorExceptionMapping" >
但是我得到了
java.lang.NoClassDefFoundError: Could not initialize class cz.instance.transl.util.ErrorExceptionMapping
如果我省略静态初始化或从 bean 的方法中调用该方法,那当然没问题。我认为初始化回调(affterPropertiesSet())在这里没有帮助。
Hey,
how one should deal with static initializations in Spring ? I mean, my bean has a static initialization
private static final Map<String, String> exceptionMapping = ErrorExceptionMapping.getExceptionMapping();
And I need to take care that ErrorExceptionMapping is loaded before. I tried this:
<bean id="errorExceptionMapping" class="cz.instance.transl.util.ErrorExceptionMapping" />
<bean id="validateService" class="cz.instance.transl.services.ValidateService" depends-on="errorExceptionMapping" >
But I got
java.lang.NoClassDefFoundError: Could not initialize class cz.instance.transl.util.ErrorExceptionMapping
If I omit the static initialization or call the method from within the bean's method, its of course fine. I suppose that Initialization callback (affterPropertiesSet()) wouldn't help here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对其他 bean 进行静态依赖并不是 Spring 的方式。
但是,如果您想使其保持静态,则可以延迟初始化它 - 在这种情况下,depends-on 可以强制执行正确的初始化顺序。
编辑:通过延迟加载,我的意思是这样的(我在这里使用holder类习惯用法的延迟初始化,可以使用其他延迟初始化习惯用法):
并使用
ExceptionMappingHolder.exceptionMapping
而不是异常映射
。Having
static
dependencies on other beans is not a Spring way.However, if you want to keep it
static
, you can initialize it lazily - in that casedepends-on
can enforce proper initialization order.EDIT: By lazy loading I mean something like this (I use lazy initialization with holder class idiom here, other lazy initialization idioms can be used instead):
and use
ExceptionMappingHolder.exceptionMapping
instead ofexceptionMapping
.您应该能够使用
@Component
注释来标记类,然后使用@Autowired(required=true)
注释添加非静态设置器来设置静态变量。这里有一个链接了解更多信息。
You should be able to mark the class with the
@Component
annotation, then add a non static setter with@Autowired(required=true)
annotation for setting the static variable.Here's a link for more info.