Spring MVC,从控制器内部调用另一个控制器 [英] Spring MVC, calling another controller from Inside a controller

查看:161
本文介绍了Spring MVC,从控制器内部调用另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个控制器来调用第二个控制器上的方法的现有代码。到目前为止我已经看到了2种实现。

I am working on an existing code that is using one controller to call a method on the 2nd controller. There are 2 implementations I have seen so far.

第1次实施

return new Controller().method(request, response);

第二次实施

@Autowired
private Controller controller.

return this.controller.method(request, response);

哪个是正确的实现,如果有任何问题,有什么问题。

Which is the right implementation, what are the problems if any with either of them.

推荐答案

你需要从另一个控制器调用方法这一事实揭示了一个可能的设计缺陷。

The mere fact that you need to call a method from another controller reveals a probable design flaw.

使用选项1,您将丢失Spring DI容器带给您的所有内容:即,其他控制器可能由Spring实例化,其中一些其他依赖项连接到它。如果你自己实例化它,即使它现在可以正常工作,因为你可能没有@Autowired / @Value依赖项,一旦你在其他资源上添加依赖项,它就会中断。此外,您已经有一个为您构建容器的实例,为什么要创建其他容器?

With option 1, you lose everything the Spring DI container brought you: namely, that other controller may be instantiated by Spring with some other dependencies wired into it. If you instantiate it yourself, even if it does work at this moment, because you probably have no @Autowired / @Value dependencies, it will break once you'll add dependencies on other resource(s). Besides, you already have an instance the container built for you, why create others ?

这篇关于Spring MVC,从控制器内部调用另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆