1 javabean的自動裝配
自動注入,減少xml文件的配置信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!-- 到入xml文件的約束 --> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:p = "http://www.springframework.org/schema/p" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"> <!-- 1 實例化Dao對象 id:完成對象的引用 class:指定需要創建的對象對應的類的完全限定名 --> < bean id = "usersDao" class = "org.guangsoft.dao.impl.UsersDaoImpl" > </ bean > <!-- 2實例化service autowire:屬性的作用,完成對象依賴之間的自動裝配 no(默認執行) byName:使用需要注入的屬性對應的set的方法名字和spring容器中的對象的id進行匹配,如果能匹配上,進行自動注入 byType:使用需要注入的屬性對應的set的方法參數類型和spring容器中的對象的類型進行匹配,如果能匹配上,進行自動注入 constructor:在byName和byType之間進行選擇(首先byName,如果byName不匹配再byType) 實際使用:byName --> < bean id = "usersService" class = "org.guangsoft.service.impl.UsersServiceImpl" autowire = "byType" > </ bean > <!-- 3實例化Action對象 --> < bean id = "usersAction" class = "org.guangsoft.action.UsersAction" autowire = "byType" > </ bean > </ beans > |
2 spring的掃描注解
使用spring的掃描注解,重構三層結構。配置更少的內容
在applicationContext.xml文件中,導入掃描的xsd
l 開啟注解掃描
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!-- 到入xml文件的約束 --> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" [ A1 ] xmlns:p = "http://www.springframework.org/schema/p" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 開啟注解掃描 base-package屬性:指定需要掃描的包,多個包之間使用,號隔開 a.b.c a.b.d a.b.e --> < context:component-scan base-package="org.guangsoft.dao.impl, org.guangsoft.service.impl,org.guangsoft.action"></ context:component-scan > </ beans > |
注解進行總結
類注解:
@controller(給web層的注解)
@service(給serivce層加的注解)
@repository(給dao層加的注解)
@component(給java類加注解,老版本spring只有這一個注解)
以上三個注解:將對應的類納入spring容器中對應的
Id:類名第一個字母小寫(默認)
如果需要自己指定id需要給三個注解加入String類的參數
@controller(“uAction”)id=uAction
@resouce(給需要依賴的對象屬性加的注解)
通過自動裝配完成需要依賴屬性的注入。
參數:name:按照byName進行自動裝配
參數:type:按照byType進行自動裝配
注解執行過程
1,加載spring的容器
2,掃描spring容器中指定包
3,掃描指定的包中,加了三個類注解的類,然后將該類納入spring容器
4,<beanid=””class=””>
5,掃描類中被加入@resource注解的屬性,然后按照自動裝配的方式進行關系建立
6,Autowrie
總結
以上就是本文關于Spring自動裝配與掃描注解代碼詳解的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:https://www.cnblogs.com/guanghe/p/6123330.html