Spring正确调用属性文件
我有一个 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。任何提示将不胜感激。
谢谢
I have a spring mvc application and I am rendering some pdfs using classes that extend AbstractPdfView. I have several pdfs and I thought it would make sense to create a helper class to put some common functionality. I then decided I wanted to add any output text to my messages_en.properties file. How do I access this file from my helper class? Right now I am creating an instance of my helper class manually. Looks like this:
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();
......
I tried having the Helper extend ApplicationContextAware but always returned null. I also tried the following with the same result:
@Autowire
private ApplicationContext context;
header = context.getMessage("myHeader", null, Locale.getDefault());
I feel like I am not using Spring correctly when creating the HelperClass manually as well. Any tips would be appreciated.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AbstractPdfView
是ApplicationObjectSupport
的子类,它有一个有用的getMessageSourceAccessor()
方法,该方法返回一个MessageSourceAccessor
,是从框架获取消息的最简单方法。只需将其传递给您的帮助程序类:然后帮助程序就可以相应地使用它。
请注意,为了使其正常工作,必须正确初始化
PdfEarningsRecordView
对象。 Spring 通常会在启动期间通过调用其ApplicationObjectSupport.setApplicationContext()
来为您完成此操作,但如果您自己实例化PdfEarningsRecordView
,则无论出于何种原因,您都必须自己调用该方法。AbstractPdfView
is a subclass ofApplicationObjectSupport
, which has a usefulgetMessageSourceAccessor()
method, which returns aMessageSourceAccessor
, which is the easiest way to get messages from the framework. Just pass that to your helper class:The helper can then use that accordingly.
Note that in order for this to work, the
PdfEarningsRecordView
object must be properly initialized. Spring will generally do this for you, by calling itsApplicationObjectSupport.setApplicationContext()
during startup, but if you instantiate aPdfEarningsRecordView
yourself, for whatever reason, you'll have to call that method yourself.