1.springIOC初識

IOC,控制反轉,從最淺顯的角度來說就是經過Spring容器來負責建立對象html

大致的實現結構java

1.首先有一個咱們須要運行的類spring

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

3.啓動容器 xml

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

5.調用對象的方法對象

簡單demoblog

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

2.建立咱們須要運行的類io

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(){
		/*
		 * 一、啓動spring容器
		 * 二、從spring容器中把helloWorld拿出來
		 * 三、對象.方法
		 */
		//啓動spring容器
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//配置文件的全路徑
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根據配置文件中的id獲取對象
		helloWorld.hello();
	}
}
相關文章
相關標籤/搜索