开发者

Spring calling properties file correctly

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 = 开发者_Go百科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


AbstractPdfView is a subclass of ApplicationObjectSupport, which has a useful getMessageSourceAccessor() method, which returns a MessageSourceAccessor, which is the easiest way to get messages from the framework. Just pass that to your helper class:

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());

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 its ApplicationObjectSupport.setApplicationContext() during startup, but if you instantiate a PdfEarningsRecordView yourself, for whatever reason, you'll have to call that method yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜