spring框架學習記錄 2

** spring學習之 ioc容器與Bean的配置**
學習視頻資源
ioc(inversion of control)控制反轉
思想,把管理對象交給spring?spring管理對象的屬性
BeanFactory接口有重載getBean方法,簡單看其中幾種

  1. Object getBean(String var1) 這種方法通過在applicationContext.xml文件中配置唯一的實體類id來創建對象,缺點是方法返回類型爲object,使用需要強轉
  2. <T> T getBean(Class<T> var1) 這種使用了泛型,通過實體類.class(反射?)的方式創建對象,因爲使用了泛型,所以返回值類型不需要強轉,但applicationContext.xml文件中不能一個class類定義多個bean,不然會報錯,案例代碼:配置文件
    調用代碼
    demo
    報錯
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.study.april.Four] is defined: expected single matching bean but found 2: fourId,fourId2
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:366)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1066)
	at com.study.april.TestBySpring.main(TestBySpring.java:18)
  1. <T> T getBean(String var1, Class<T> var2)
    既不用強轉,也不用擔心配置多個class Bean的問題

依賴注入的幾種方式

  1. 通過property方法設置name和value是調用類中的set方法,如果類中沒有set方法,property會報錯

  2. 通過有參構造方法和xml配置constructor-arg標籤來注入 在這裏插入圖片描述
    沒用啊

  3. 通過p命名空間注入
    pName
    注意:命名空間也依賴類的set方法,不寫同樣報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章