關於Spring?html
提供對象容器。java
1.Spring的概述?spring
2.Spring框架的獲取?app
經過maven來獲取。框架
3.開發spring的程序?maven
Spring的注入(所謂的注入就是給對象加入數據。)測試
1)開發spring程序,主要是經過spring來獲取對象。this
實現的步驟:spa
1)在項目中引入spring的相應的jar包:.net
2)編寫實體類:
public class Girl { public String getGirlname() { return girlname; }
public void setGirlname(String girlname) { this.girlname = girlname; }
private String girlname; } |
3)在spring的配置文件裏,applicationContext文件裏作bean對象的註冊:
<!-- 將對象註冊到spring的容器裏 --> <bean id="girl1" class="com.jinglin.spring.bean.Girl"> <property name="girlname"> <value>鳳姐</value> </property> </bean> |
4)在測試類編寫經過spring來獲取剛剛註冊的這個對象:
//首先要獲取spring的配置 ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); Girl girl1 = (Girl) ctx.getBean("girl1"); System.out.println("這女生的姓名:"+girl1.getGirlname()); |
4.Spring的注入問題?
所謂的注入,就是在spring中如何註冊對象(構建對象的方式)。
1)屬性的注入。也就是在構建對象的時候加入屬性值。
<bean id="girl1" class="com.jinglin.spring.bean.Girl"> <property name="girlname"> <value>鳳姐</value> </property> </bean> |
2)構造器注入,構造方法的注入。
<bean id="girl2" class="com.jinglin.spring.bean.Girl"> <constructor-arg type="java.lang.String" value="范冰冰"></constructor-arg> </bean> |
3)若是屬性是集合,那麼數據如何注入。
<bean id="girl3" class="com.jinglin.spring.bean.Girl"> <property name="girlname"> <value>張白癡</value> </property> <property name="habbies"> <list> <value>吃飯</value> <value>睡覺</value> </list> </property> <!-- 鍵值對集合的注入 --> <property name="score"> <map> <entry> <!-- 這是一個鍵 --> <key> <value>數學</value> </key> <!-- 這是一個值 --> <value>78</value> </entry> <entry> <key> <value>英語</value> </key> <value>92</value> </entry> </map> </property> </bean> |
4)引用其餘bean:
<bean id="boy1" class="com.jinglin.spring.bean.Boy"> <property name="name"> <value>張三</value> </property> <!-- 在bean中引用其它的bean --> <property name="girl" ref="girl3"></property> </bean> |
5.bean的做用域?
1)若是沒有設置bean的scope屬性,這個bean的做用域是屬於共享實例的,所謂的共享實例指的是全部的bean對象都引用的是同一個實例對象。默認的bean的scope值爲singleton
2)非共享實例,也就是每次在產生的bean對象都是不同的。
scope的值爲prototype。
6.自動裝配
屬性中的名字和bean的名字同樣的時候,那麼就自動注入數據。
<!-- 自動裝配的示例,autowire:byName,經過名字自動裝配,也就是husband裏有一個wife的屬性名。 自動裝配的意思就是須要去找wife的bean的id名字,若是找到了就自動把bean的數據給這個屬性--> <bean id="husband" class="com.jinglin.bean.Husband" autowire="byName"> <property name="name" value="張三"></property> <!-- <property name="wife" ref="wife"></property> --> </bean> <bean id="wife" class="com.jinglin.bean.Wife"> <property name="name" value="鳳姐"></property> </bean> |