Spring正确调用属性文件

时间:2011-03-31 15:47:30

标签: java spring properties messages

我有一个spring mvc应用程序,我使用扩展AbstractPdfView的类渲染一些pdf。我有几个pdf,我认为创建一个辅助类来放置一些常用功能是有意义的。然后我决定将任何输出文本添加到messages_en.properties文件中。如何从助手类访问此文件?现在我手动创建一个辅助类的实例。看起来像这样:

   public class PdfEarningsRecordView extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        HelperClass helper = new HelpderClass();
......

我尝试让Helper扩展ApplicationContextAware但总是返回null。我也尝试了以下相同的结果:

@Autowire
private ApplicationContext context;
header = context.getMessage("myHeader", null, Locale.getDefault());

我觉得在手动创建HelperClass时我没有正确使用Spring。任何提示将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:2)

AbstractPdfViewApplicationObjectSupport的子类,它有一个有用的getMessageSourceAccessor()方法,它返回MessageSourceAccessor,这是从框架中获取消息的最简单方法。只需将它传递给你的助手类:

public class PdfEarningsRecordView extends AbstractPdfView {

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {

    HelperClass helper = new HelperClass(getMessageSourceAccessor());

然后帮助者可以相应地使用它。

请注意,为了使其正常工作,必须正确初始化PdfEarningsRecordView对象。 Spring通常会在启动时通过调用ApplicationObjectSupport.setApplicationContext()为您执行此操作,但如果您自己实例化PdfEarningsRecordView,无论出于何种原因,您都必须自己调用该方法。