解釋@Component @Controller @Service @Repository

對Spring的註解標籤剛剛接觸,所以就找了幾個常用的,記錄下,感覺註解用了之後,會在*.xml文件中大大減少配置量。以前我們每個Bean都得到配置文件中配置關聯下。spring2.5後,引入了完整的annotation配置註解,使得我們的程序配置更簡單更容易維護。 

@Component;@Controller;@Service;@Repository 

      在annotaion配置註解中用@Component來表示一個通用註釋用於說明一個類是一個spring容器管理的類。即就是該類已經拉入到spring的管理中了。而@Controller, @Service, @Repository是@Component的細化,這三個註解比@Component帶有更多的語義,它們分別對應了控制層、業務邏輯層、持久層的類。 

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


例如: 

@Repository("userDao") 
public class UserDaoImpl  implements UserDao{ 

   ........................................ 



聲明瞭UserDaoImpl  在Spring容器中叫userDao這個名字。 

@Service是用於服務層的IServiceImpl類文件,功能與@Repository類似。 



另外標籤:@Autowired 用來注入。 

例如: 

@Autowired 
private UserDao userDao; 

這樣就注入進去了,相當於我們new了個實現類,我們就無需寫setter方法了。 

我們還得有配置文件進行配置: 

<?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:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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.zxr.manager"> 
        <context:include-filter type="regex" expression=".*DaoImpl"/> 
        <context:include-filter type="regex" expression=".*ServiceImpl"/> 
    </context:component-scan> 
</beans> 

這樣就把com.zxr.manager包下的所有.*DaoImpl,.*ServiceImpl都註冊關聯到Spring容器中去了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章