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

@Controller

您可以使用标准 Spring Bean 定义来定义控制器 Bean。 这@Controllerstereotype 允许自动检测,并与 Spring 一般支持保持一致 用于检测@Component类路径中的类和自动注册 bean 定义 对他们来说。它还充当带注释的类的构造型,指示其角色为 Web 组件。spring-doc.cadn.net.cn

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

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

	// ...
}
1 扫描org.example.web包。
@Configuration
@ComponentScan("org.example.web") (1)
class WebConfig {

	// ...
}
1 扫描org.example.web包。

@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 WebFlux 不再检测到 仅基于类型级的控制器@RequestMapping注解。 请启用基于类的代理,否则接口还必须具有@Controller注解。