Spring static initialization of a bean

前端 未结 2 1880
天涯浪人
天涯浪人 2021-01-21 09:17

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

private static final Map exce         


        
相关标签:
2条回答
  • 2021-01-21 09:49

    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.

    0 讨论(0)
  • 2021-01-21 09:51

    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.

    0 讨论(0)
提交回复
热议问题