Using Spring IoC to set up enum values

后端 未结 13 1923
名媛妹妹
名媛妹妹 2020-11-30 06:06

Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded i

13条回答
  •  时光取名叫无心
    2020-11-30 06:31

    I have done it in the following way:

    @Component
    public class MessageSourceHelper {
        @Inject
        public MessageSource injectedMessageSource;
    
        public static MessageSource messageSource;
    
        public static String getMessage(String messageKey, Object[] arguments, Locale locale) {
            return messageSource.getMessage(messageKey, arguments, locale);
        }
    
        @PostConstruct
        public void postConstruct() {
            messageSource = injectedMessageSource;
        }
    

    }

    That way you can easily use it in the enum to get messages in the following way:

    MessageSourceHelper.getMessage(key, arguments, locale);
    

提交回复
热议问题