Getting localized message from resourceBundle via annotations in Spring Framework

前端 未结 2 936
一个人的身影
一个人的身影 2020-12-07 22:04

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



        
2条回答
  •  一个人的身影
    2020-12-07 22:34

    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();
    
    }
    

    And

    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;
        }
    

提交回复
热议问题