Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC, calling another controller from Inside a controller

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.

1st Implementation

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

2nd Implementation

@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.

like image 740
3coins Avatar asked Oct 11 '12 20:10

3coins


People also ask

Can we call controller inside controller?

In general, you won't use one controller from another one since: Controllers usually return a result of a type intended to be used by the MVC framework.

Can we call controller method from another controller method?

use App\Http\Controllers\OtherController; class TestController extends Controller { public function index() { //Calling a method that is from the OtherController $result = (new OtherController)->method(); } }

How do you call a controller in spring?

Spring REST Controller Test Go to URL https://localhost:8080/Spring-Controller/rest and you should get following output. Now let's provide the name parameter value in the URL, go to https://localhost:8080/Spring-Controller/rest/person/get?name=Pankaj and you will get following JSON response.


2 Answers

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

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 ?

like image 121
Costi Ciudatu Avatar answered Sep 22 '22 13:09

Costi Ciudatu


If you do a call in between Controllers, either there is a flaw or you want to make a redirection, which is totally valid. If redirection is the case just return in your controller method as follow:

return "redirect:/yourDestinationControllerPath";
like image 27
Diego Duarte Avatar answered Sep 20 '22 13:09

Diego Duarte