对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

声明

你可以通过在 Servlet 的 WebApplicationContext 中使用标准的 Spring bean 定义来定义控制器 bean。@Controller 刻板注解(stereotype)支持自动检测,这与 Spring 在类路径中检测 @Component 类并为其自动注册 bean 定义的通用支持保持一致。它还作为被注解类的刻板注解,表明该类作为 Web 组件的角色。spring-doc.cadn.net.cn

要启用对此类 @Controller bean 的自动检测,您可以将组件扫描添加到您的 Java 配置中,如下例所示:spring-doc.cadn.net.cn

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

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

	// ...
}

以下示例展示了与前述示例等效的 XML 配置:spring-doc.cadn.net.cn

<?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:p="http://www.springframework.org/schema/p"
	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 模板进行渲染。spring-doc.cadn.net.cn

AOP 代理

在某些情况下,你可能需要在运行时使用 AOP 代理来包装控制器。 一个例子是,如果你选择直接在控制器上使用 @Transactional 注解。 在这种情况下,特别是对于控制器,我们建议使用基于类的代理。 当你直接在控制器上使用此类注解时,Spring 会自动采用这种方式。spring-doc.cadn.net.cn

如果控制器实现了某个接口,并且需要 AOP 代理,则可能需要显式配置基于类的代理。例如,使用 @EnableTransactionManagement 时,可以更改为 @EnableTransactionManagement(proxyTargetClass = true);使用 <tx:annotation-driven/> 时,可以更改为 <tx:annotation-driven proxy-target-class="true"/>spring-doc.cadn.net.cn

请注意,从 6.0 版本开始,在使用接口代理的情况下,Spring MVC 不再仅根据接口上类级别的 @RequestMapping 注解来检测控制器。 请启用基于类的代理,否则该接口还必须添加 @Controller 注解。