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.
You are doing completely wrong. See
Costi Ciudatu's
answer for what is wrong.Solution: I advice you to have
service layer and dao layer classes
associated with yourcontrollers
. Suppose you haveAccountController
, you will haveAccountService
class(interface + implementation) andAccountDao
(interface + implementation).Now if user logs in (
LoginController
) and you need account so you will autowireAccountService
inLoginController
, you will get user's account details fromAccountService
methods.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:
Sounds like you need to refactor the code. Extract what is common between the two controllers into a separate class, then call that from either controller.
The second one is correct because you will not make an instance of it every time. The @Autowired annotation injects the object into your code when needed.
Check this http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html
But there is a @Controller annotation and you should be using that for controllers and @Service for beans you want to autowire.
The first needs more work, firstly do you really want to create a new instance of Controller class everytime?
The second uses a pattern known as dependency injection or inversion of control which is nicer. Let spring manage scope of the bean for you, by default it will create only 1 instance of the Controller class however if at some point (for some reason) you don't want this behaviour its straightforward to create many instances...
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 ?