如何避免以编程方式为枚举获取 bean?

How to avoid getting bean programmatically for Enums?

我有 Enum:

public enum EmployeeErrorCode {
    DELETE_SUCCESS,

    //... Other enumerators

    @Override
    public String toString(){
        ApplicationContext ctx = ContextLoader
                                         .getCurrentWebApplicationContext();
        MessageSource messageSource = (MessageSource) ctx
                                         .getBean("messageSource"); //How to avoid this?
        switch (this) {
        case DELETE_SUCCESS:
            return messageSource.getMessage("deleteEmployee.success", 
                                          null, LocaleContextHolder.getLocale());

        //... Other cases

        default:
            return null;
        }
    }
}

toString 方法中,我为任何 Enumerator 指定了消息,但我使用 getBean 方法以编程方式获取适当的 bean。我怎样才能避免这种情况?

我试图通过

注入bean
@Autowired
MessageSource messageSource;

但是没用。事实上,messageSource 只是 null。有没有办法完全正确地做到这一点?

如果 MessageSource 是一个打开 properties 文件的 bean,那么例如如果您的属性文件名为 Messages.properties,那么您可以使用

ResourceBundle bundle = ResourceBundle.getBundle("Messages", LocaleContextHolder.getLocale());
String message = bundle.getString("deleteEmployee.success");

编辑:另一种可能的方法是将 MessageSource 注入您的枚举(来自我在 的解决方案的想法),如下所示:

public enum EmployeeErrorCode {
    DELETE_SUCCESS {
        @Override
        public String toString() {
             return messageSource.getMessage("deleteEmployee.success", null, LocaleContextHolder.getLocale());
        }
    },
    //... Other enumerators

    private MessageSource messageSource;

    static class EnumInitializer {
        @Autowired
        private MessageSource messageSource;

        @PostConstruct
        public void init() {
            for(EmployeeErrorCode errorCode : EmployeeErrorCode.values() {
                errorCode.messageSource = getMessageSource();
            }
        }

        public MessageSource getMessageSource() {
            return messageSource;
        }
    }
}

不过我觉得另一个比较干净