【问题标题】:How to get localized message in custom tag in Spring MVC如何在 Spring MVC 的自定义标签中获取本地化消息
【发布时间】:2015-12-05 11:50:40
【问题描述】:

在我的应用程序中有一个自定义标签(扩展 BodyTagSupport)。需要从标签中的属性文件中获取本地化消息。我在 dispatcher-servlet.xml 文件中定义了 messageSource。现在我该如何使用它在标签文件中。请帮助我。

    <bean name="messageSource"
    class="com.application.core.TestResourceBundleMessageResource">
    <property name="basename" value="welcome" />

【问题讨论】:

    标签: java spring spring-mvc dependency-injection


    【解决方案1】:

    如果您可以在 applicationContext 中定义消息源而不是调度程序 servlet 配置,则以下是一种解决方案:

    创建以下类:

    public class SpringContextUtil implements ApplicationContextAware {
        private static ApplicationContext applicationContext;     
    
        public void setApplicationContext(ApplicationContext context) throws BeansException {
            applicationContext = context;
        }
    
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    }
    

    在您的 applicationContext 文件中添加:

    现在在你的自定义标签类中你可以这样做:

    (TestResourceBundleMessageResource)SpringContextUtil.getApplicationContext().getBean("messageSource");
    

    这是因为我们现在有了对 applicationContext 的引用,我们可以通过调用 SpringContextUtil 的静态 get 方法来获取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2021-08-06
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多