對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容器中去了。
解釋@Component @Controller @Service @Repository
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
myeclipse DB Browser 連接mysql 報錯的解決方案
霁颜
2018-08-27 19:02:25
Spring整合mybatis
LeesurYoo
2018-08-27 17:33:12
Hibernate解決懶加載問題
LeesurYoo
2018-08-27 17:33:11
【SSH】驗證碼程序實現
YYS_518
2018-08-27 17:07:38
出現“org.hibernate.QueryException: could not resolve property”錯誤的解決,針對多對一的表的結構
YYS_518
2018-08-27 17:07:38
SpringBoot依賴積累
晚春
2018-08-27 16:38:01
SpringBoot配置積累
晚春
2018-08-27 16:37:59
SpringBoot的常用系統變量
晚春
2018-08-27 16:37:58
SpringMVC + ajaxfileupload的多文件上傳
wei_ge163
2018-08-27 07:35:19
springMVC詳解
dsmflmsa
2018-08-27 00:38:14
Spring國際化實現
dsmflmsa
2018-08-27 00:37:49
getCurrentSession 與 openSession() 的區別
dsmflmsa
2018-08-27 00:37:49
struts2 註解配置攔截器 實例
dsmflmsa
2018-08-27 00:37:45