此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
声明
您可以通过在
Servlet 的WebApplicationContext
.这@Controller
stereotype 允许自动检测,
与 Spring 对检测的常规支持一致@Component
类路径中的 classes
以及为它们自动注册 bean 定义。它还充当
annotated 类,指示其作为 Web 组件的角色。
要启用此类@Controller
beans 中,你可以将组件扫描添加到
您的 Java 配置,如下例所示:
-
Java
-
Kotlin
-
Xml
@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 模板进行渲染。
AOP 代理
在某些情况下,您可能需要在运行时使用 AOP 代理装饰控制器。
例如,如果您选择@Transactional
注解直接放在
控制器。在这种情况下,特别是对于控制器,我们建议
使用基于类的代理。此类 Comments 自动出现这种情况
直接在控制器上。
如果控制器实现了一个接口,并且需要 AOP 代理,则可能需要
显式配置基于类的代理。例如,使用@EnableTransactionManagement
您可以更改为@EnableTransactionManagement(proxyTargetClass = true)
和<tx:annotation-driven/>
您可以更改为<tx:annotation-driven proxy-target-class="true"/>
.
请记住,从 6.0 开始,使用接口代理时,Spring MVC 不再检测
仅基于类型级的控制器@RequestMapping 注解。
请启用基于类的代理,否则接口还必须具有@Controller 注解。 |