@Component注解、@Service注解、@Repository注解、@Controller注解區別


---------------------------------------------------------------------------------------------------

  Spring 2.5 中除了提供 @Component 注釋外,還定義了幾個擁有特殊語義的注釋,它們分別是:@Repository、@Service 和 @Controller。
在目前的 Spring 版本中,這 3 個注釋和 @Component 是等效的,但是從注釋類的命名上,很容易看出這 3 個注釋分別和持久層、業務層和控制層(Web 層)相對應。
雖然目前這3 個注釋和 @Component 相比沒有什么新意,但 Spring 將在以后的版本中為它們添加特殊的功能。
所以,如果 Web 應用程序采用了經典的三層分層結構的話,最好在持久層、業務層和控制層分別采用上述注解對分層中的類進行注釋。

@Service用於標注業務層組件 服務 (注入dao)

@Controller用於標注控制層組件(如struts中的action)控制器(注入服務)

@Repository用於標注數據訪問組件,即DAO組件

@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。(把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)

@Component: 定義Spring管理Bean

擴展:

@Component擴展,被@Service注解的POJO類表示Service層實現,從而見到該注解就想到Service層實現,使用方式和@Component相同;

@Component擴展,被@Controller注解的類表示Web層實現,從而見到該注解就想到Web層實現,使用方式和@Component相同;

@Component,@Service,@Controller,@Repository注解的類,並把這些類納入進spring容器中管理。 

下面寫這個是引入component的掃描組件 
<context:component-scan base-package=”com.mmnc”>    

其中base-package為需要掃描的包(含所有子包) 
       1、@Service用於標注業務層組件 
       2、@Controller用於標注控制層組件(如struts中的action) 
       3、@Repository用於標注數據訪問組件,即DAO組件. 
       4、@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。    
           @Service 
           public class UserServiceImpl implements UserService { } 
           @Repository 
           public class UserDaoImpl implements UserDao { } getBean的默認名稱是類名(頭字母小寫),如果想自定義,可以@Service(“***”)       
                   這樣來指定,這種bean默認是單例的,如果想改變,可以使用@Service(“beanName”) 
           @Scope(“prototype”)來改變。可以使用以下方式指定初始化方法和銷毀方法(方法名任意): @PostConstruct public void init() { } 

  

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> 

  

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; 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM