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.
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.
use App\Http\Controllers\OtherController; class TestController extends Controller { public function index() { //Calling a method that is from the OtherController $result = (new OtherController)->method(); } }
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.
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 ?
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With