@Component 相當于執行個體化類的對象。
通過在 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:component-scan base-package="com.zchen" />
- </beans>
注:前面講要使用注解需要配置: <context:annotation-config />但如果使用了@Component就不需要加它了,因為:<context:component-scan base-package="com.zchen">裡面預設了<context:annotation-config />。
Java代碼
- @Component ( "userService" )
- public class UserService {
@Service用于标注業務層元件、
@Controller用于标注空竹曾元件(如Struts中的action)
@Repository用于标注資料通路元件即DAO元件
@Component泛指元件,當元件不好歸類的時候我們可以使用這個注解進行标注,(現在可以都用此注解)