Spring註解@Component、@Repository、@Service、@Controlle

很長時間沒作web項目都把之前學的那點框架知識忘光了,今天把之前作的一個項目翻出來看一下發現用·@Component標記一個組件,而網上有的用@Service標記組件,我暈就查了一下資料:java

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

@Service用於標註業務層組件spring

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

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

@Component泛指組件,當組件很差歸類的時候,咱們可使用這個註解進行標註。spa

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

在一個稍大的項目中,若是組件採用xml的bean定義來配置,顯然會增長配置文件的體積,查找以及維護起來也不太方便。 
Spring2.5爲咱們引入了組件自動掃描機制,他在類路徑下尋找標註了上述註解的類,並把這些類歸入進spring容器中管理。
它的做用和在xml文件中使用bean節點配置組件時同樣的。要使用自動掃描機制,咱們須要打開如下配置信息:.net

<?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:annotation-config />
	<context:component-scan base-package=」com.eric.spring」>   
</beans>

1.annotation-config是對標記了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等註解的類進行對應的操做使註解生效。
2.base-package爲須要掃描的包(含全部子包),負責掃描那些類有註解。prototype

 

getBean的默認名稱是類名(頭字母小寫),若是想自定義,能夠@Service(「aaaaa」)這樣來指定。
這種bean默認是「singleton」的,若是想改變,可使用@Scope(「prototype」)來改變。code

可使用如下方式指定初始化方法和銷燬方法:component

@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。

相關文章
相關標籤/搜索