1 javabean的自動裝配
自動注入,減少xml文件的配置信息。
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!-- 到入xml文件的約束 -->
3 <beans xmlns="http://www.springframework.org/schema/beans"
4 xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
7 <!-- 1 實例化Dao對象 id:完成對象的引用 class:指定需要創建的對象對應的類的完全限定名 -->
8 <bean id="usersDao" class="org.guangsoft.dao.impl.UsersDaoImpl">
9 </bean>
10 <!-- 2實例化service autowire:屬性的作用,完成對象依賴之間的自動裝配 no(默認執行) byName:使用需要注入的屬性對應的set的方法名字和spring容器中的對象的id進行匹配,如果能匹配上,進行自動注入 11 byType:使用需要注入的屬性對應的set的方法參數類型和spring容器中的對象的類型進行匹配,如果能匹配上,進行自動注入 constructor:在byName和byType之間進行選擇(首先byName,如果byName不匹配再byType) 12 實際使用:byName -->
13 <bean id="usersService" class="org.guangsoft.service.impl.UsersServiceImpl"
14 autowire="byType">
15 </bean>
16 <!-- 3實例化Action對象 -->
17 <bean id="usersAction" class="org.guangsoft.action.UsersAction"
18 autowire="byType">
19 </bean>
20 </beans>
21
2 spring的掃描注解
使用spring的掃描注解,重構三層結構。配置更少的內容
在applicationContext.xml文件中,導入掃描的xsd
l 開啟注解掃描
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!-- 到入xml文件的約束 -->
3 <beans xmlns="http://www.springframework.org/schema/beans"
4 xmlns:context="http://www.springframework.org/schema/context" [ A1 ] 5 xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-4.1.xsd 10 ">
11 <!-- 開啟注解掃描 base-package屬性:指定需要掃描的包,多個包之間使用,號隔開 a.b.c a.b.d a.b.e -->
12 <context:component-scan 13 base-package="org.guangsoft.dao.impl, 14 org.guangsoft.service.impl,org.guangsoft.action"></context:component-scan>
15 </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, <bean id=”” class=””>
5, 掃描類中被加入@resource注解的屬性,然后按照自動裝配的方式進行關系建立
6, Autowrie