繁体   English   中英

如何在自定义Velocity工具中加载/访问bean(@Resource)

[英]How to load/access a bean (@Resource) in a custom Velocity tool

我意识到这是一件需要做的事情,但是我试图从一个自定义的Velocity工具访问我的Spring messageSource bean。

在我们大多数的代码库中,我可以像这样设置一个成员变量并加载它:

@Resource(name = "messageSource")
private AbstractMessageSource _msgSource;

但是,在这种情况下,我认为这不会加载bean,因为Velocity工具的实例化方式不允许正常的bean加载发生。 或者,它不想为应用程序范围的Velocity工具初始化bean。

该工具在toolbox.xml中设置如下:

<tool>
    <key>calendarTool</key>
    <scope>application</scope>
    <class>...</class>
</tool>

我无法在网上找到任何可以解释如何执行此操作或为何不起作用的内容。

不知道为什么它不起作用,但是您是否尝试了在没有注释的情况下检索它,例如:

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
AbstractMessageSource _msgSource = (AbstractMessageSource )ctx.getBean("messageSource");

我所做的是在渲染Velocity模板的代码中,我使用applicationContext.getBean(“ messageSource”)从applicationContext检索了消息源,然后将该MessageSource直接放入用于渲染我的VelocityContext中关键字“ messageSource”下的模板:

VelocityContext velocityContext = new VelocityContext();
velocityContext.put("messageSource", applicationContext.getBean("messageSource"));

然后,无论何时我想呈现一个消息密钥,例如在HTML电子邮件中,它看起来都像:

<td>messageSource.getMessage("my.message.key", null, $locale)</td>

其中$ locale是一个java.util.Locale对象,我也手动将其放置在VelocityContext中。 如果我需要消息的任何参数,则可以使用上下文中放入的列表工具从通常在模板中在那里创建的参数列表中获取数组。 附带说明一下,您可以使用org.springframework.ui.velocity.VelocityEngineUtils类中的帮助器方法来帮助您在控制器或Webflow代码中或任何其他可能渲染模板的位置渲染Velocity模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM