標籤:utf-8 全路徑 5.x print contex 設定檔 highlight 配置 建立對象
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 {@Testpublic 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初識