1

我意识到这是一件有点时髦的事情,但我正在尝试从自定义 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>

我无法在网上找到任何解释如何做到这一点或为什么它不起作用的东西。

4

2 回答 2

0

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

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
AbstractMessageSource _msgSource = (AbstractMessageSource )ctx.getBean("messageSource");
于 2009-09-25T22:18:35.237 回答
0

我所做的是在渲染 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 模板,或者您可能正在渲染模板的任何其他地方。

于 2009-09-25T22:28:05.733 回答