對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容器中去了。