我可以注射"在隐式杰克逊序列化之前,从消息资源到模型对象的值是什么?

时间:2015-11-03 14:33:44

标签: spring spring-mvc spring-boot jackson

我有一个使用Spring Boot / Spring MVC构建的REST API,使用Jackson的隐式JSON序列化。

现在,在隐式序列化之前,我想"注入"一些UI文本从消息资源到Jackson转换为JSON的对象。有没有一些简洁明了的方法呢?

作为一个简化的示例,下面我想将Section标题设置为用户可见的值,完全基于其SectionType

(当然,我可以在SectionType中对UI文本进行硬编码,但我宁愿将它们分开,在资源文件中,因为它更干净,并且它们可能在某些时候被本地化。我可以& #39; t autowire MessageSource在未经Spring管理的实体/模型对象中。)

@Entity
public class Entry {

     // persistent fields omitted

     @JsonProperty
     public List<Sections> getSections() {
         // Sections created on-the-fly, based on persistent data
     }

}

public class Section {    
    public SectionType type;
    public String title; // user-readable text whose value only depends on type       
}

public enum SectionType {
    MAIN,
    FOO,
    BAR; 

    public String getUiTextKey() {
        return String.format("section.%s", name());
    }
}

@RestController中的某个地方:

@RequestMapping(value = "/entry/{id}", method = RequestMethod.GET)
public Entry entry(@PathVariable("id") Long id) {
    return service.findEntry(id);
}

我希望与代码(messages_en.properties)分开的用户界面文字:

section.MAIN=Main Section
section.FOO=Proper UI text for the FOO section
section.BAR=This might get localised one day, you know

我想在Spring管理的服务/ bean中做些什么(使用Messagesa very simple helper包裹MessageSource):

section.title = messages.get(section.type.getUiTextKey())

请注意,如果我调用entry.getSections()并为每个设置标题,则不会影响JSON输出,因为章节是在getSections()中动态生成的。

我是否必须一直进行自定义deseriazation,或是否有更简单的方法在杰克逊序列化之前挂钩模型对象?

很抱歉,如果问题不清楚;如果需要,我可以尝试澄清。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,你可以围绕返回Section的每个控制器方法编写一个Aspect。

我写了一个简单的例子。您必须使用消息源修改它。

控制器:

@RestController
@RequestMapping("/home")
public class HomeController {
    @RequestMapping("/index")
    public Person index(){
        Person person = new Person();
        person.setName("evgeni");
        return person;
    }
}

方面

    @Aspect
    @Component
    public class MyAspect {
        @Around("execution(public Person com.example..*Controller.*(..))")//you can play with the pointcut here
        public Object addSectionMessage(ProceedingJoinPoint pjp) throws Throwable {

            Object retVal = pjp.proceed();
            Person p = (Person) retVal; // here cast to your class(Section) instead of Person
            p.setAge(26);//modify the object as you wish and return it
            return p;
        }

    }

由于该方面也是@Component,因此您可以@Autowire

相关问题