java - Spring正确调用属性文件

标签 java spring properties message

我有一个 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。任何提示将不胜感激。

谢谢

最佳答案

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,无论出于何种原因,您都必须自己调用该方法。

关于java - Spring正确调用属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5502591/

相关文章:

java - 为什么当我在另一个类中显式使用一个类的公共(public)函数时,java不会给出编译错误

java - 将 Map 对象存储在另一个 Map 中

java - 搜索并列出 .m2(本地)maven 存储库

Spring Cloud 和 Eureka : java. lang.IllegalStateException:没有可用于 ACCOUNTS-SERVICE 的实例

java - 如何将 "find or create"方法提取到抽象类? ( Spring 数据 Jpa)

Python属性描述符设计: why copy rather than mutate?

java - 定时器启动/停止参数

spring - 基本 spring hibernate struts2 应用程序的 Maven 原型(prototype)

java - 如何从文件 config.properties 中读取 persistence.xml <jta-data-source> 的标签值

python - 属性 getter/setter 在 Python 2 中无效