此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

声明

您可以使用标准 Spring Bean 定义来定义控制器 Bean Servlet的WebApplicationContext.这@Controller刻板印象允许自动检测, 与 Spring 通用支持对检测保持一致@Component类路径中的类 并为它们自动注册 bean 定义。它也充当了对 带注释的类,指示其作为 Web 组件的角色。spring-doc.cadn.net.cn

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

@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 模板进行视图分辨率和渲染。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注解。