宣告

您可以使用 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 進行 meta-annotation 註解,以指示控制器,該控制器的每個方法都繼承類型層級的 @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 註解。