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

声明

你可以通过在Servlet的WebApplicationContext中使用标准的Spring bean定义来定义控制器bean。@Controller注解允许自动检测,与Spring对classpath中的@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-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注解。