1 javabean的自動裝配
自動注入,減少xml文件的配置信息。
<?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"> </bean> <!-- 2實例化service autowire:屬性的作用,完成對象依賴之間的自動裝配no(默認執行) byName:使用需要注入的屬性對應的set的方法名字和spring容器中的對象的id進行匹配,如果能匹配上,進行自動注入byType:使用需要注入的屬性對應的set的方法參數類型和spring容器中的對象的類型進行匹配,如果能匹配上,進行自動注入constructor:在byName和byType之間進行選擇(首先byName,如果byName不匹配再byType) 實際使用:byName --> <bean id="usersService" autowire="byType"> </bean> <!-- 3實例化Action對象--> <bean id="usersAction" autowire="byType"> </bean></beans>
2 spring的掃描註解
使用spring的掃描註解,重構三層結構。配置更少的內容
在applicationContext.xml文件中,導入掃描的xsd
l 開啟註解掃描
<?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屬性:指定需要掃描的包,多個包之間使用,號隔開abc abd abe --> <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自動裝配與掃描註解代碼詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站:
基於註解的組件掃描詳解
spring配置掃描多個包問題解析
如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!