Spring static initialization of a bean

lisak picture lisak · Nov 22, 2010 · Viewed 35.4k times · Source

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.

Answer

dcp picture dcp · Nov 22, 2010

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.