Spring註解@Component、@Repository、@Service、@Controller區別

來源:互聯網
上載者:User

標籤:

Spring 2.5 中除了提供 @Component 注釋外,還定義了幾個擁有特殊語義的注釋,它們分別是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,

這 3 個注釋和 @Component 是等效的,但是從注釋類的命名上,很容易看出這 3 個注釋分別和持久層、業務層和控制層(Web 層)相對應。雖然目前這3 個注釋和 @Component

相比沒有什麼新意,但 Spring 將在以後的版本中為它們添加特殊的功能。所以,如果 Web 應用程式採用了經典的三層分層結構的話,最好在持久層、業務層和控制層分別採用上述註解對分層中的類進行注釋。

@Service用於標註業務層組件

@Controller用於標註控制層組件(如struts中的action)

@Repository用於標註資料訪問組件,即DAO組件

@Component泛指組件,當組件不好歸類的時候,我們可以使用這個註解進行標註。

    @Service      public class VentorServiceImpl implements iVentorService {         }      @Repository      public class VentorDaoImpl implements iVentorDao {       }  

在一個稍大的項目中,如果組件採用xml的bean定義來配置,顯然會增加設定檔的體積,尋找以及維護起來也不太方便。 Spring2.5為我們引入了組件自動掃描機制,他在類路徑下尋找標註了上述註解的類,並把這些類納入進spring容器中管理。
它的作用和在xml檔案中使用bean節點配置組件時一樣的。要使用自動掃描機制,我們需要開啟以下配置資訊:

代碼

<?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.eric.spring”>     </beans> 

1.component-scan標籤預設情況下自動掃描指定路徑下的包(含所有子包),將帶有@Component、@Repository、 @Service、@Controller標籤的類自動註冊到spring容器。對標記了 Spring‘s @Required、@Autowired、JSR250‘s @PostConstruct、@PreDestroy、@Resource、JAX-WS‘s @WebServiceRef、EJB3‘s @EJB、JPA‘s @PersistenceContext、@PersistenceUnit等註解的類進行對應的操作使註解生效(包含了annotation- config標籤的作用)。

getBean的預設名稱是類名(頭字母小寫),如果想自訂,可以@Service(“aaaaa”)這樣來指定。這種bean預設是“singleton”的,如果想改變,可以使用@Scope(“prototype”)來改變。

可以使用以下方式指定初始化方法和銷毀方法:

@PostConstruct  public void init() {   }   @PreDestroy  public void destory() {   }  

注入方式:

把DAO實作類別注入到action的service介面(注意不要是service的實作類別)中,注入時不要new 這個注入的類,因為spring會自動注入,如果手動再new的話會出現錯誤,
然後屬性加上@Autowired後不需要getter()和setter()方法,Spring也會自動注入。  

在介面前面標上@Autowired注釋使得介面可以被容器注入,如:

    @Autowired      @Qualifier("chinese")      private Man man;   

當介面存在兩個實作類別的時候必須使用@Qualifier指定注入哪個實作類別,否則可以省略,唯寫@Autowired。

Spring註解@Component、@Repository、@Service、@Controller區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.