Search This Blog

Sunday 8 July 2012

The MessageSourceAware Interface

While we can use the ApplicationContext for Internationalization, we may also need the functionality to be available to normal beans.
For this the beans need to implement the MessageSourceAware interface. Consider the bean class below:
public class MessageAwareBean implements MessageSourceAware {

    private MessageSource paramMessageSource;

    @Override
    public void setMessageSource(MessageSource paramMessageSource) {
        this.paramMessageSource = paramMessageSource;
    }

    @Override
    public String toString() {

        return "MessageAwareBean: "
                + this.paramMessageSource.getMessage("argument.required",
                        new Object[] { "Application Context" }, "Required",
                        null);
    }
}
The class implements the setMessageSource() method which is called by the ApplicationContext to pass a reference to its MessageSource.According the java docs the method is invoked
after population of normal bean properties but before an init callback like
InitializingBean's afterPropertiesSet or a custom init-method. Invoked before 
ApplicationContextAware's setApplicationContext.
To test the code:
public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-locale.xml");
    MessageAwareBean messageAwareBean = (MessageAwareBean) applicationContext.getBean("msgAwareBean");
    System.out.println(messageAwareBean);
}
The output of the code indicates that the MessageSource was successfully made aware to the bean:
MessageAwareBean: The 'Application Context' argument is required

No comments:

Post a Comment