spring bean的Spring静态初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4247705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:13:13  来源:igfitidea点击:

Spring static initialization of a bean

springstaticstatic-initialization

提问by lisak

Hey, how one should deal with static initializations in Spring ? I mean, my bean has a static initialization

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

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

And I need to take care that ErrorExceptionMapping is loaded before. I tried this:

而且我需要注意之前加载了 ErrorExceptionMapping 。我试过这个:

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

如果我省略静态初始化或从 bean 的方法中调用该方法,当然没问题。我想初始化回调 (affterPropertiesSet()) 在这里没有帮助。

回答by dcp

You should be able to mark the class with the @Componentannotation, then add a non static setter with @Autowired(required=true)annotation for setting the static variable.

您应该能够使用@Component注释标记类,然后添加一个带有@Autowired(required=true)注释的非静态设置器来设置静态变量。

Here's a linkfor more info.

这是了解更多信息的链接

回答by axtavt

Having staticdependencies on other beans is not a Spring way.

static其它的bean的依赖不是春路。

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

但是,如果您想保留它static,您可以延迟初始化它 - 在这种情况下depends-on可以强制执行正确的初始化顺序。

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.exceptionMappinginstead of exceptionMapping.

并使用ExceptionMappingHolder.exceptionMapping代替exceptionMapping.