Spring基礎 ----IOC(2)

Spring 自動掃描註解


@Component
public class Person {

    @Resource(name="stu")
    private Student student;
}

@Component("stu")
public class Student{

}

*************************************************

<?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:context="http://www.springframework.org/schema/context"
       xmlns:IOC.context="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--開啓 自動類掃描/依賴註解掃描-->
    <context:component-scan base-package="IOC.context"/>

    在類上標註@Component
    spring 容器會爲該類創建對象 bean,如果@Component values爲bean的ID值,如果爲空,
    則該bean ID爲該類名(首字母小寫)
    類似的註解還有: @Controller @Service @Repository ,作用跟@Component一樣

    執行@Resource註解的流程
    查看bean中的屬性或者方法上有沒有@Resource
    1、	如果該註解的屬性name的值爲" ",則會按照屬性的名稱和spring中的ID進行匹配,
         如果匹配成功,則賦值,如果匹配不成功,**則按照類型進行匹配**,如果類型匹配不成功,則報措
    2、	如桌該註解的屬性name不爲" ",則按照該name值和spring中的ID值進行匹配,如果匹配則賦值,不匹配則報錯
</beans>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章