Java 在Spring中从RestController或Hibernate截取对象实例,然后再将其返回到客户端

Java 在Spring中从RestController或Hibernate截取对象实例,然后再将其返回到客户端,java,spring,hibernate,Java,Spring,Hibernate,我正在开发一个翻译服务,目前在另一个服务中工作。例如: public Profile getById(int chainId, int profileId, Integer languageId) { Profile profile = profileRepository.getById(chainId, profileId); translationService.translate(profile, languageId); // Here return profil

我正在开发一个翻译服务,目前在另一个服务中工作。例如:

public Profile getById(int chainId, int profileId, Integer languageId) {
    Profile profile = profileRepository.getById(chainId, profileId);
    translationService.translate(profile, languageId); // Here
    return profile;
}
现在,为了避免在所有应用程序的每个服务方法上使用translate方法,并且由于我只有来自控制器的用户的语言,我希望在每个概要文件和任何其他对象返回到客户端之前执行translate方法

我试图在自定义拦截器中实现,但它似乎没有返回我要返回的对象的实例。有人能帮忙吗


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

解决方案是使用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开头的所有方法,例如,通过这个建议,我们在将对象发送给Jackson之前拦截它。getCustomUserDetails方法来自AccessApicController,这是我们为控制器提供所需信息而创建的一个类。

您能发布您的尝试吗?这听起来不对。你只需要传递区域设置,并使用不同的翻译文件来制作你的i18n。@winter我没有找到任何方法,所以我不能发布任何其他内容。。。我只是要求在我的对象返回给客户机进行翻译之前截取它。@niVeR为什么错了?我们通过数据库来做!不要。。。您正在修改持久化实体。相反,您应该在视图层中进行转换。否则返回一个中间对象,并使用Springs I18N支持来执行转换,而不是自己滚动。