声明

您可以通过在 Servlet 的WebApplicationContext.这@Controllerstereotype 允许自动检测, 与 Spring 对检测的常规支持一致@Component类路径中的 classes 以及为它们自动注册 bean 定义。它还充当 annotated 类,指示其作为 Web 组件的角色。spring-doc.cadn.net.cn

要启用此类@Controllerbeans 中,你可以将组件扫描添加到 您的 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注解直接放在 控制器。在这种情况下,特别是对于控制器,我们建议 使用基于类的代理。此类 Comments 自动出现这种情况 直接在控制器上。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注解。