1. 程式人生 > 實用技巧 >spring學習

spring學習

1.ApplicationContext 代表 Spring IOC容器。

  IOC:(Inversion of Control)反轉資源獲取的方向,即由容器為其管理的類分配資源。

  DI:(Dependence Injection)依賴注入,將容器配置好的引數注入到其管理的類中。

2.ClassPathXmlApplicationContext 是ApplicationContext 介面 的 實現類,並從類路徑下載入配置檔案。

3.獲取bean,bean介面在 ClassPathXmlApplicationContext 的副介面 BeanFactory中進行初始化。

  //2.從IOC容器中獲取bean例項(利用id定位bean)

  HelloWorld hw = (HelloWorld)ctx.getBean("helloWorld");

  //2.用型別獲取(要求IOC容器中只有一個該型別的bean)

  HelloWorld hw = ctx.getBean(HelloWorld.class);

4.DI(依賴注入):(還有一種工廠方法注入(不推薦使用))

    屬性注入:(最常用)通過get、set方法注入,對應配置標籤<property>

<bean id="helloWorld" class="com.springstudy1.beans.HelloWorld">
	<property name="name" value="spring"></property>
</bean>

    構造器注入:通過構造方法注入,對應配置標籤<congstructor-arg>

<bean id="car" class="com.springstudy1.beans.Car">
	<constructor-arg index="0" value="Audi" type="String"></constructor-arg>
	<constructor-arg index="1" value="ShangHai" type="String"></constructor-arg>
	<constructor-arg index="2" value="300000" type="double"></constructor-arg>
</bean>
<!-- 通過index位置或type型別區分過載構造器 <bean id="car2" class="com.springstudy1.beans.Car"> <constructor-arg index="0" value="Benchi" type="String"></constructor-arg> <constructor-arg index="1" value="German" type="String"></constructor-arg> <constructor-arg index="2" value="240" type="int"></constructor-arg> </bean>
public Car(String brand, String crop, double price) {
    super();
    this.brand = brand;
    this.crop = crop;
    this.price = price;
}

public Car(String brand, String crop, int maxspeed) {
    super();
    this.brand = brand;
    this.crop = crop;
    this.maxspeed = maxspeed;
}
    

總結:

各個資源類通過配置檔案將需要的資源告知容器,容器在資源初始化的時候將各個資源類所需的資源分配給他們。

(減少了資源初始化的次數以及佔用的硬體資源,只需要在容器中初始化一次即可)