天天看點

@Component @Service @Controller @Repository注解使用

@Component 相當于執行個體化類的對象。

通過在 classpath 中通過自動掃描方式把組建納入 spring 容器管理。

要使用自動掃描機制我們需要打開一下配置資訊:

Bean.xml代碼    

@Component @Service @Controller @Repository注解使用
  1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"   
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.        xmlns:context="http://www.springframework.org/schema/context"   
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.            http://www.springframework.org/schema/beans/spring-beans-2.5 .xsd  
  7.            http://www.springframework.org/schema/context  
  8.            http://www.springframework.org/schema/context/spring-context-2.5 .xsd">  
  9.            <context:component-scan base-package="com.zchen" />  
  10. </beans>  

注:前面講要使用注解需要配置: <context:annotation-config />但如果使用了@Component就不需要加它了,因為:<context:component-scan base-package="com.zchen">裡面預設了<context:annotation-config />。

Java代碼    

@Component @Service @Controller @Repository注解使用
  1. @Component ( "userService" )  
  2. public   class  UserService {  

 @Service用于标注業務層元件、

 @Controller用于标注空竹曾元件(如Struts中的action)

 @Repository用于标注資料通路元件即DAO元件

 @Component泛指元件,當元件不好歸類的時候我們可以使用這個注解進行标注,(現在可以都用此注解)

繼續閱讀