I am new to Spring-mvc. In my first tutorial I am having a doubt, we create a servelet of DispatcherServlet in web.xml and mark our controller using @contorller annotation. Then using @Requestmapping annotation we filter url for function to be invoked.
How Spring searches for controller in the webapp? Which function actually invoked in DispatcherServelet to create a instance of controller class? Can i have multiple controller in my application?
How Spring searches for controller in the webapp?
Spring container scans through all of the packages specified through @ComponentScan
annotation (or using component-scan
in xml config) and when you mark your bean class with stereotype annotation like @Controller
, Spring container will create the instance (by default singleton scope) of your controller class and maps the url along with the request method type(like GET
, POST
, PUT
, etc..). The other stereotype annotation are listed here (like @Service
, etc..) and the container creates objects for these types as well.
Which function actually invoked in DispatcherServelet to create a instance of controller class?
Spring core container creates the instances for all beans annotated with stereotypes (as explained above during container start up) and then
Dispatcherservlet
uses HandlerMapping to map the urls to the controller methods and RequestMappingHandlerMapping
implementation is being used by default and when the request comes, it will be delegated to the respective the controller method, you can look here.
Can I have multiple controllers in my application?
Yes, you can define multiple controllers in your application. In a typical web application project, you would see many controller classes each mapped with the respective urls and the business logic being handled through their service classes.
I suggest you refer this to understand on how the spring web flow works.