St.Antario
St.Antario

Reputation: 27425

How to avoid getting bean programmatically for Enums?

I have the 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;
        }
    }
}

In the toString nethod I specified the messages for any Enumerator, but I used getBean method to programmatically get the appropriate bean. How can I avoid that?

I tried to inject the bean via

@Autowired
MessageSource messageSource;

but it didn't work. In fact, messageSource was just null. Is there a way to do that corretly at all?

Upvotes: 0

Views: 592

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81568

If MessageSource is a bean that opens a properties file, then for example if your properties file is called Messages.properties, then you can use

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

EDIT: Another possible method is to inject the MessageSource into your enums (idea from my solution at Java Generics and Enum, loss of template parameters ), like so:

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;
        }
    }
}

But I think the other one is a bit cleaner.

Upvotes: 1

Related Questions