@Component 相當於實例化類的對象,其他三個注解可以理解為@Component的子注解或細化。
在annotaion配置注解中用@Component來表示一個通用注釋用於說明一個類是一個spring容器管理的類,此類將有spring掃描並加入容器參與ioc。即就是該類已經拉入到spring的管理中了。
通過在 classpath 中通過自動掃描方式把組建納入 spring 容器管理。
要使用自動掃描機制我們需要打開一下配置信息:
Bean.xml代碼
- <?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:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5 .xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5 .xsd">
- <!--<context:annotation-config />-->
- <context:component-scan base-package="com.zchen" />
- <!-- 包含annotation-config。spring可以自動去掃描base-pack下面或者子包下面的java文件,如果掃描到有@Component @Controller@Service等這些注解的類,則把這些類注冊為bean-->
- </beans>
注:前面講要使用注解需要配置: <context:annotation-config />但如果使用了@Component就不需要加它了,因為:<context:component-scan base-package="com.zchen">里面默認了<context:annotation-config />。
而@Controller, @Service, @Repository是@Component的細化,這三個注解比@Component帶有更多的語義,它們分別對應了控制層、服務層、持久層的類。
@Component泛指組件,當組件不好歸類的時候我們可以使用這個注解進行標注,(現在可以都用此注解,可以只使用單一組件)