Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring static initialization of a 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();

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.

like image 760
lisak Avatar asked Dec 02 '25 20:12

lisak


1 Answers

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

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

and use ExceptionMappingHolder.exceptionMapping instead of exceptionMapping.

like image 94
axtavt Avatar answered Dec 04 '25 13:12

axtavt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!