通过 Spring Framework 中的注释从 resourceBundle 获取本地化消息 [英] Getting localized message from resourceBundle via annotations in Spring Framework

查看:24
本文介绍了通过 Spring Framework 中的注释从 resourceBundle 获取本地化消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做吗?目前它是这样做的:

Is it possible to do this ? Currently it is done like this :

<bean id="resource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>content.Language</value> 
        </list>
    </property>
</bean>

@Autowired
protected MessageSource resource;

protected String getMessage(String code, Object[] object, Locale locale) {
    return resource.getMessage(code, object, locale);
}

有没有办法像通过@Value 注释获取属性一样?

Is there a way for it to be like getting properties via @Value annotation ?

<util:properties id="generals" location="classpath:portlet.properties" />

    @Value("#{generals['supported.lang.codes']}")
    public String langCodes;

因为必须调用该方法通常很好,但是例如在单元测试时,这很痛苦......在某些情况下,webdriver 的 PageObject 模式,其中对象没有初始化,这将是很有帮助

Because having to call the method is usually fine, but for instance when unit testing, this is pain in ... ... Well in some cases, webdriver's PageObject pattern where objects don't have no initialization, this would be really helpful

推荐答案

重点是这仅对单元测试有用.在实际应用中,Locale 是不能硬编码在注解中的运行时信息.区域设置根据运行时中的用户区域设置确定.

The point is that this is really useful only for Unit Testing. In real application, Locale is a runtime information that cannot be hardcoded in the annotation. Locale is decided based on Users locales in Runtime.

顺便说一句,您可以自己轻松实现这一点,例如:

Btw you can easily implement this by yourself, something like :

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Localize {

    String value();

}

public class CustomAnnotationBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        Class clazz = bean.getClass();
        do {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Localize.class)) {
                    // get message from ResourceBundle and populate the field with it
                }
            }
            clazz = clazz.getSuperclass();
        } while (clazz != null);
        return bean;
    }

这篇关于通过 Spring Framework 中的注释从 resourceBundle 获取本地化消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆