从资源包通过注释的Spring框架入门本地化消息 [英] Getting localized message from resourceBundle via annotations in Spring Framework

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

问题描述

是否有可能做到这一点?目前,它是这样做的:

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

推荐答案

的一点是,这仅仅是单元测试非常有用。在实际应用中,语言环境是指不能在注释硬$ C $光盘运行时信息。区域设置是基于运行用户的语言环境决定的。

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框架入门本地化消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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