在发送结果之前,我们希望在JSON响应中添加公共字段(时间戳,版本等)。我们不想在每个控制器中执行此操作。在spring mvc中有没有优雅的方法呢?
另一个类似的问题是,如果参数验证失败,如何返回相同的JSON响应。
答案 0 :(得分:1)
是的。你可以使用Spring AOP。您可以拦截您编写的每个服务并从一个地方添加参数。例如,使用Spring Around Advice。注意你需要自己编写返回JsonNode的addParameters函数。祝你好运!
public class DoAroundMethod implements MethodInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(DoAroundMethod.class);
@Autowired
ObjectMapper mapper;
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
LOG.debug("****SPRING AOP**** DoAroundMethod: Method name : "
+ methodInvocation.getMethod().getName());
LOG.debug("****SPRING AOP**** DoAroundMethod: Method name : "
+ methodInvocation.getMethod().getName());
LOG.debug("****SPRING AOP**** DoAroundMethod: Method arguments : "
+ Arrays.toString(methodInvocation.getArguments()));
// same with MethodBeforeAdvice
LOG.debug("****SPRING AOP**** DoAroundMethod: Before method executing!");
try {
// proceed to original method call
Object result = methodInvocation.proceed();
// same with AfterReturningAdvice
if(result!=null){
//LOG.debug("Return value "+result.toString());
try{
JsonNode jN = mapper.readTree(result.toString());
result=addParameters(jN);
}catch(JsonParseException e){
LOG.debug("****SPRING AOP**** DoAroundMethod: When JsonParse throws Exception!");
return result;
}
}
LOG.debug("****SPRING AOP**** DoAroundMethod: After method executing!");
return result;
} catch (IllegalArgumentException e) {
// same with ThrowsAdvice
LOG.debug("****SPRING AOP**** DoAroundMethod: When method throws Exception!");
throw e;
}
}
然后将此建议分配给您拥有的所有服务,假设它们都以* Service.java结尾
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>regexAdvisor</value>
</list>
</property>
</bean>
答案 1 :(得分:0)
也许是自定义杰克逊插件或ResponseBodyAdvice
? (see this blog post for more details)。