03-spring_配置bean
<!-- 配置bean
class : bean的全類名,通過反射的方式在IOC容器中創(chuàng)建Bean,所以要求Bean中必須有無參數(shù)的構(gòu)造器
? ? ? id:標識容器中的bean,id唯一
-->
?
在SpringIOC容器讀取Bean配置創(chuàng)建Bean實例之前,必須對他進行實例化,只有在容器實例化后,才能從IOC容器中獲取Bean實例并使用。
Spring提供了兩種類型的IOC容器實現(xiàn)
----BeanFactory IOC容器的基本實現(xiàn)
----ApplicationContext提供了更多的高級特性,是BeanFactory的子接口
前者是Spring框架的基礎(chǔ)設置,面向Spring本身;
后者是面向使用Spring框架的開發(fā)者,幾乎所有的應用場合都使用后者,而非前者。
?
ApplicationContext的主要實現(xiàn)類:
----ClassPathXmlApplicationContext : 從類基路徑下加載配置文件
----FileSystemXmlApplicationContext : 從文件系統(tǒng)中加載配置文件
ConfigurableApplicationContext擴展于ApplicationContext,新增兩個主要方法:
refresh()和close(),讓ApplicationContext具有啟動,刷新和關(guān)閉上下文的能力
?
ApplicationContext在初始化上下文時就實例化所有單利bean
WebApplicationContext是專門為WEB應用而準備 ,它允許從相對于WEB根目錄的路徑中完成初始化工作
?
?
依賴注入(屬性注入,構(gòu)造器注入,工廠方法模式注入)
屬性注入:就是<property name="username" value="jim"/>
構(gòu)造器注入:
使用構(gòu)造器注入屬性值可以指定參數(shù)的位置和參數(shù)的類型(可混用),以區(qū)分重載的構(gòu)造器。
?
Car.java
package com.demo.beans;public class Car {private String brand;private String corp;private int price;private int maxspeed;public Car(String brand, String corp, int price) {this.brand= brand;this.corp = corp;this.price = price;}@Overridepublic String toString() {return this.brand+this.price;} }<bean id="car" class="com.demo.beans.Car"><constructor-arg value="Audi"></constructor-arg><constructor-arg value="Shanghai"></constructor-arg><constructor-arg value="10000"></constructor-arg><!-- <constructor-arg value="10000" index="2"></constructor-arg> --><!-- <constructor-arg value="10000" type="int"></constructor-arg> --></bean>
?
轉(zhuǎn)載于:https://www.cnblogs.com/boucher/p/5738246.html
總結(jié)
以上是生活随笔為你收集整理的03-spring_配置bean的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MAC下安装多版本JDK和切换几种方式
- 下一篇: unix环境高级编程-进程间通信