声明

您可以在 Servlet 的 WebApplicationContext 中使用标准的 Spring bean 定义来定义控制器 bean。`@Controller` 注解是一种原型(stereotype),它允许自动检测,与 Spring 对类路径中 `@Component` 类进行检测并为其自动注册 bean 定义的通用支持保持一致。它也作为被注解类的原型,表明其作为 Web 组件的角色。

要启用 `@Controller` 这类 bean 的自动检测,您可以将组件扫描添加到您的 Java 配置中,如下例所示

  • Java

  • Kotlin

  • Xml

@Configuration
@ComponentScan("org.example.web")
public class WebConfiguration {

	// ...
}
@Configuration
@ComponentScan("org.example.web")
class WebConfiguration {

	// ...
}
<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"
	   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">

	<context:component-scan base-package="org.example.web"/>

	<!-- ... -->

</beans>

@RestController 是一个组合注解,它本身使用 `@Controller` 和 `@ResponseBody` 进行元注解,用于指示一个控制器,该控制器中的每个方法都继承了类型级别的 `@ResponseBody` 注解,因此直接将内容写入响应体,而不是通过视图解析和 HTML 模板渲染。

AOP 代理

在某些情况下,您可能需要在运行时使用 AOP 代理来装饰控制器。一个例子是您选择将 `@Transactional` 注解直接放在控制器上。在这种情况下,特别是对于控制器,我们建议使用基于类的代理。当直接在控制器上使用此类注解时,这会自动实现。

如果控制器实现了接口,并且需要 AOP 代理,您可能需要显式配置基于类的代理。例如,使用 `@EnableTransactionManagement` 时,您可以改为 `@EnableTransactionManagement(proxyTargetClass = true)`;使用 `` 时,您可以改为 ``。

请注意,从 6.0 版本开始,使用接口代理时,Spring MVC 不再仅根据接口上的类型级别 `@RequestMapping` 注解来检测控制器。请启用基于类的代理,否则接口也必须带有 `@Controller` 注解。