1. 程式人生 > >1.springIOC初識

1.springIOC初識

tex xmlns brush mon 1.0 林誌玲 運行 out 角度

IOC,控制反轉,從最淺顯的角度來講就是通過Spring容器來負責創建對象

大體的實現結構

1.首先有一個我們需要運行的類

2.在spring專屬的xml配置文件中配置該類

3.啟動容器

4.從該容器中獲取此類的對象

5.調用對象的方法

簡單demo

1.導包,最基本的是spring.jar和commons-logging.jar

2.創建我們需要運行的類

public class HelloWorld {
	public void hello(){
		System.out.println("hello world");
	}
}

3.編寫applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--beans裏面的每個bean就是一個需要容器啟動的類 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
     <!--每個bean的id一般都命名為該類名的首字母小寫的名字-->
	<bean id="helloWorld" class="HelloWorld的全類名"></bean>
    <!--每一個alias都是一個別名,name就是上面定義的id,alias就是別名-->
	<alias name="helloWorld" alias="王五"/>
	<alias name="helloWorld" alias="林誌玲"/>
	<alias name="helloWorld" alias="趙六"/>
</beans>

4.啟動容器,獲取對象,調用方法

public class HelloWorldTest {
	@Test
	public void test(){
		/*
		 * 1、啟動spring容器
		 * 2、從spring容器中把helloWorld拿出來
		 * 3、對象.方法
		 */
		//啟動spring容器
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//配置文件的全路徑
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根據配置文件中的id獲取對象
		helloWorld.hello();
	}
}

  

1.springIOC初識