声明

您可以使用 Servlet 的 WebApplicationContext 中的标准 Spring bean 定义来定义控制器 bean。@Controller 注解允许自动检测,与 Spring 对类路径中 @Component 类的通用支持以及为其自动注册 bean 定义相一致。它还作为被注解类的构造型,指示其作为 Web 组件的角色。

要启用此类 @Controller bean 的自动检测,您可以将组件扫描添加到 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 注解。在这种情况下,对于控制器,我们建议使用基于类的代理。对于直接在控制器上的此类注解,情况会自动如此。

如果控制器实现了一个接口,并且需要 AOP 代理,您可能需要明确配置基于类的代理。例如,使用 @EnableTransactionManagement,您可以将其更改为 @EnableTransactionManagement(proxyTargetClass = true);使用 <tx:annotation-driven/>,您可以将其更改为 <tx:annotation-driven proxy-target-class="true"/>

请记住,从 6.0 版本开始,对于接口代理,Spring MVC 不再仅仅基于接口上的类型级别 @RequestMapping 注解来检测控制器。请启用基于类的代理,否则接口也必须具有 @Controller 注解。
© . This site is unofficial and not affiliated with VMware.