在Spring返回客户端之前,在Spring中拦截RestController或Hibernate中的对象实例

时间:2018-04-12 15:26:19

标签: java spring hibernate

我正在开发目前在其他服务中运行的翻译服务。例如:

public Profile getById(int chainId, int profileId, Integer languageId) {
    Profile profile = profileRepository.getById(chainId, profileId);
    translationService.translate(profile, languageId); // Here
    return profile;
}

现在,为了避免在所有应用程序的每个服务方法上使用translate方法,并且因为我只有控制器中的用户语言,我想在每个Profile(和任何其他)之前执行translate方法object)返回给客户端。

我尝试在自定义拦截器中实现HandlerInterceptor,但它似乎并没有返回我返回的对象的实例。有人可以帮忙吗?

另一种方法是翻译来自Hibernate中的select的每个对象,但我也没有找到任何好的解决方案......

1 个答案:

答案 0 :(得分:0)

解决方案是使用Spring AOP。可能这个问题没有得到很好的解释,但我们需要的是拦截用户向后端询问的对象的方法,因为他们能够创建自己的翻译并将它们保存在数据库中。我们必须为每个用户返回具有正确翻译的模型,这些用户在他们的个人资料中具有本地化。这是我们拦截它的方式:

@Component
@Aspect
public class TranslatorInterceptor extends AccessApiController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public TranslationService translationService;

    @Pointcut("execution(* com.company.project.api.controller.*.get*(..))")
    public void petitionsStartWithGet() { }

    @Pointcut("execution(* com.company.project.api.controller.*.list*(..))")
    public void petitionsStartWithList() { }

    @Pointcut("execution(* com.company.project.api.controller.*.find*(..))")
    public void petitionsStartWithFind() { }

    @AfterReturning(pointcut = "petitionsStartWithGet() || petitionsStartWithList() || petitionsStartWithFind()", returning = "result")
    public void getNameAdvice(JoinPoint joinPoint, Object result){
        translationService.translate(result, getCustomUserDetails().getLanguageId());
        logger.debug("Translating " + result.getClass().toString());
    }
}

我们在这里做的是“观察”“控制器”包中以'get','list'或'find'(例如getById()开头)的所有方法,并通过这个建议,我们拦截之前的对象是送给杰克逊的。方法getCustomUserDetails来自AccessApiController,这是我们为控制器提供所需信息的类。