Spring MVC 使用@Controller注解定義一個(gè)控制器

2018-07-26 14:02 更新

[Original] The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to.

@Controller注解表明了一個(gè)類是作為控制器的角色而存在的。Spring不要求你去繼承任何控制器基類,也不要求你去實(shí)現(xiàn)Servlet的那套API。當(dāng)然,如果你需要的話也可以去使用任何與Servlet相關(guān)的特性和設(shè)施。

[Original] The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations (see the next section).

@Controller注解可以認(rèn)為是被標(biāo)注類的原型(stereotype),表明了這個(gè)類所承擔(dān)的角色。分派器(DispatcherServlet)會(huì)掃描所有注解了@Controller的類,檢測(cè)其中通過(guò)@RequestMapping注解配置的方法(詳見(jiàn)下一小節(jié))。

[Original] You can define annotated controller beans explicitly, using a standard Spring bean definition in the dispatcher’s context. However, the @Controller stereotype also allows for autodetection, aligned with Spring general support for detecting component classes in the classpath and auto-registering bean definitions for them.

當(dāng)然,你也可以不使用@Controller注解而顯式地去定義被注解的bean,這點(diǎn)通過(guò)標(biāo)準(zhǔn)的Spring bean的定義方式,在dispather的上下文屬性下配置即可做到。但是@Controller原型是可以被框架自動(dòng)檢測(cè)的,Spring支持classpath路徑下組件類的自動(dòng)檢測(cè),以及對(duì)已定義bean的自動(dòng)注冊(cè)。

[Original] To enable autodetection of such annotated controllers, you add component scanning to your configuration. Use the spring-context schema as shown in the following XML snippet:

你需要在配置中加入組件掃描的配置代碼來(lái)開(kāi)啟框架對(duì)注解控制器的自動(dòng)檢測(cè)。請(qǐng)使用下面XML代碼所示的spring-context schema:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.springframework.samples.petclinic.web"/>

    <!-- ... -->

</beans>


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)