目录
@Repository @Service @Controller @component
Spring 从2.5版开始引入注解,用户可以在Spring MVC 中使用@Controller、@RequestMapper、@RequestParam、@ModelAttribute等类似的注解。
@Controller
org.springframework.stereotype.Controller
用于指定Spring类的实例是一个控制器。使用@Controller 注解的类不需要继承特定的父类或者实现特定的接口,Controller接口的实现类只能处理一个单一请求动作,而@Controller 注解的控制器可以支持同时处理多个请求动作,更加灵活。
@Controller用于标记一个类,使用它标记的类就是一个Spring MVC Controller 对象,即一个控制器类。Spring 使用扫描机制查找应用程序中所有基于注解的控制器类,分发处理器会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapper 注解,而使用@RequestMapper 注解的方法才是真正处理请求的处理器。为了保证Spring 能找到控制器,需要完成两件事情:
- 在Spring MVC 的配置文件的头文件中引入 spring-context。
- 使用<context:component-scan/>元素,该元素的功能:启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为Spring 的Bean。
- base-package属性指定了需要扫描的类包,应该将所有的控制器类都放在该包中。
<context:component-scan base-package="com.damin.controller"/>
springmvc-config.xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--