0

Can any one please explain me the difference between declaring a class with @Controller vs (declaring it with @Scope + define a bean in the applicationContext.xml)

Here is my situation.

Approach 1: declare the class with @Scope and add bean definition in the applicationContext.xml

AbcController.java:

package my.app.controller;
    @Scope("singleton")
    @RequestMapping(value = "/abc")
    public class AbcController {
        @RequestMapping(value = "/simulate_abc", method = RequestMethod.GET)
        public String getFactorsForSimulate(ModelMap model) {
            model.addAttribute("Welcome to the simulations page");
            return "simulate_abc";
        }
    }

applicationContext.xml

<bean id="abcController" class="my.app.controller.AbcController"/>

Approach 2: declare the class with @Controller and no bean definition in applicationContext.xml

package my.app.controller;    
@Controller
    @RequestMapping(value="/abc")
    public class AbcController {
           @RequestMapping(value = "/simulate_abc", method = RequestMethod.GET)
            public String getFactorsForSimulate(ModelMap model) {
                model.addAttribute("Welcome to the simulations page");
                return "simulate_abc";
         }
    }

Here, both the approaches are giving me the expected results (taking me to 'simulate_abc.jsp' with the message attached to the model). I would like to understand, why is Approach1 not failing? Although it has a RequestMapping, since it is not declared as a controller, how come the 'view' is getting resolved? I have a feeling that the Approach1 is wrong, as it does not satisfy 'C' part in the spring 'MVC'.

Karthik
  • 75
  • 2
  • 8
  • You can notify the user that marked it like so: @Luiggi. – Sotirios Delimanolis Jun 02 '14 at 18:24
  • @Luiggi. May I know why the question is tagged duplicate? Provided link does not seem to answer my question. I found the issue. The views are getting resolved due to the declaration 'RequestMapping' for the method. And I am sure, this is NOT a duplicate question. – Karthik Jun 02 '14 at 18:24

1 Answers1

1

For RequestMappingHandlerMapping there is no difference, just look at RequestMappingHandlerMapping#isHandler(), both annotations works.

However, for others HandlerMappings like in AbstractControllerUrlHandlerMapping hierarchy, @Controller annotation does the matter.

Note that in Spring MVC a Controller is any class with any method that a HandlerMapping maps to a request. A HandlerAdapter is also needed to execute it.

Jose Luis Martin
  • 10,459
  • 1
  • 37
  • 38