關於Spring註解 @Service @Component @Controller @Repository 用法

@Component 至關於實例化類的對象,其餘三個註解能夠理解爲@Component的子註解或細化。java

 在annotaion配置註解中用@Component來表示一個通用註釋用於說明一個類是一個spring容器管理的類,此類將有spring掃描並加入容器參與ioc。即就是該類已經拉入到spring的管理中了。spring

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

要使用自動掃描機制咱們須要打開一下配置信息:component

Bean.xml代碼   xml

  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:annotation-config />-->
  10.            <context:component-scan base-package="com.zchen" />  
  11.            <!-- 包含annotation-config。spring能夠自動去掃描base-pack下面或者子包下面的java文件,若是掃描到有@Component @Controller@Service等這些註解的類,則把這些類註冊爲bean-->
  12. </beans>  

 

 

注:前面講要使用註解須要配置: <context:annotation-config />但若是使用了@Component就不須要加它了,由於:<context:component-scan base-package="com.zchen">裏面默認了<context:annotation-config />。對象

而@Controller, @Service, @Repository是@Component的細化,這三個註解比@Component帶有更多的語義,它們分別對應了控制層、服務層、持久層的類。string

@Component泛指組件,當組件很差歸類的時候咱們能夠使用這個註解進行標註,(如今能夠都用此註解,能夠只使用單一組件)it

Java代碼  

@Repository標籤是用來給持久層的類定義一個名字,讓Spring根據這個名字關聯到這個類。io

例如:class

@Repository(value="userDao")-----也能夠直接寫@Repository("userDao"),若是沒有命名,default name 是class name: UserDaoImpl
public class UserDaoImpl  implements UserDao{
   ........................................
}

保證這個類在bean.xml中<context:component-scan base-pakage="com.czhen">com.czhen pakage dir下。

註解Repository後能夠直接使用@autowire 直接注入 managerImpl中,如:

 

@Autowire

private UserDaoImpl userDaoImpl;

 

通常來講@Controller(控制層) 是action入口,調用@Service(業務層) ,Service再調用@Repository (持久層)完成數據持久化。

相關文章
相關標籤/搜索