查了一些網上的其他部落格,發現幾個註解本質上沒有什麼區別,至少在spring2.5版本里,這幾個註解本質是一樣的(當然,新的版本有什麼變化目前還沒細查),命名不一樣主要是為了區分類的作用和所屬層級:
@Repository:持久層,用於標註資料訪問元件,即DAO元件。
@Service:業務層,用於標註業務邏輯層主鍵。
@Controller:控制層,用於標註控制層元件。
@Component:當你不確定是屬於哪一層的時候使用。
之所以區分開幾種型別,一是spring想在以後的版本中為它們新增特殊技能,二是這種分層的做法使web架構更清晰,易讀性與維護性更好。
/**
* Indicates that an annotated class is a "Service", originally defined by Domain-Driven
* Design (Evans, 2003) as "an operation offered as an interface that stands alone in the
* model, with no encapsulated state."
*
* <p>May also indicate that a class is a "Business Service Facade" (in the Core J2EE
* patterns sense), or something similar. This annotation is a general-purpose stereotype
* and individual teams may narrow their semantics and use as appropriate.
*
* <p>This annotation serves as a specialization of {@link Component @Component },
* allowing for implementation classes to be autodetected through classpath scanning.
*
* @author Juergen Hoeller
* @since 2.5
* @see Component
* @see Repository
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
*/
String value() default "";
}
從@service的原始碼看,service仍然是使用了@Component註解(@Controller與@Repository與service一樣,這裡就不貼原始碼了)。
component即元件,相當於xml配置檔案中的bean申明,通過spring的自動掃描機制,在規定的類路徑中尋找標註了@Component,@Service,@Repository,@Controller註解的類,並把這些類納入進容器中進行管理。getBean的預設名稱是類名(頭字母小寫),並且是單例的,如果想自定義,可以使用@Service(“beanName”)@Scope(“prototype”)來改變。
/**自動掃描base-package目錄下的所有檔案,包括子目錄**/
<context:component-scan base-package="com.user.*"/>