views:

241

answers:

1

I have a view class that extends AbstractExcelView

public class ExportExcelParticipantsView extends AbstractExcelView  {
...
}

I would like to inject a MessageSource to this bean. Is this possible?

I use a ResourceBundleViewResolver to resolve views (in this case)

<bean id="resourceBundleViewResolver"
 class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
 <!-- Classpath needs to have views.properties -->
 <property name="basename" value="views" />
 <!-- This view resolver is the first one used -->
 <property name="order" value="0"/>  
 <property name="defaultParentView" value="parent-view"/>
</bean>

Is it so that this view class is instantiated each time the view is requested and thus injecting a message source to this class is harder than usual? Is it even possible?

At the moment I pass the MessageSource as a model attribute from the controller to the view. Is it possible to avoid this?

+1  A: 

I suggest creating a simple subclass of ResourceBundleViewResolver. This subclass would override the loadView() method and inject the MessageSource into the View object:

public class MyViewResolver extends ResourceBundleViewResolver {

    @Override
    protected View loadView(String viewName, Locale locale) throws Exception {
        View view = super.loadView(viewName, locale);
        if (view instanceof MessageSourceAware) {   
            ((MessageSourceAware)view).setMessageSource(getApplicationContext());
        }
        return view;
    }
}

The MessageSource that is injected here is the appcontext's own message source, but you could inject any one you need to here. Also, your View class would need to implement MessageSourceAware.

skaffman