Bean的Spring静态初始化 [英] Spring static initialization of a bean

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

问题描述

嘿, Spring应该如何处理静态初始化?我的意思是,我的bean有一个静态初始化

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();

而且我需要注意ErrorExceptionMapping之前已加载.我试过了:

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

但我知道了

java.lang.NoClassDefFoundError: Could not initialize class cz.instance.transl.util.ErrorExceptionMapping

如果我省略了静态初始化或从bean的方法中调用该方法,那么它当然很好.我想初始化回调(affterPropertiesSet())在这里无济于事.

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.

推荐答案

对其他bean具有static依赖项不是Spring的方法.

Having static dependencies on other beans is not a Spring way.

但是,如果要保留它static,则可以延迟对其进行初始化-在这种情况下,depends-on可以强制执行正确的初始化顺序.

However, if you want to keep it static, you can initialize it lazily - in that case depends-on can enforce proper initialization order.

通过延迟加载,我的意思是这样的(我在这里将懒惰的初始化与holder类的习惯用法结合使用,也可以使用其他的懒惰的初始化习惯用法):

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):

private static class ExceptionMappingHolder {
    private static final Map<String, String> exceptionMapping = 
        ErrorExceptionMapping.getExceptionMapping(); 
}

,并使用ExceptionMappingHolder.exceptionMapping代替exceptionMapping.

这篇关于Bean的Spring静态初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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