阿里雲大學JavaWeb開發系列課程:Spring框架入門第二講

接上一講

6.hello spring

步驟:導入相關jar包

spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-context-support-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
commons-logging-1.1.1.jar

編寫spring配置文件(名稱可以自定義)

思考:

hello對象是由spring容器創建的。

hello對象屬性是由spring容器來設置的。

這個過程就叫控制反轉。

控制的內容:指誰來控制對象的創建;傳統的應用程序對象的創建是由程序本身控制的。使用spring後,是由spring來創建對象的。

反轉:正轉指程序來創建對象,反轉指程序本身不去創建對象,而變爲被動的接收對象。

總結:以前對象是由程序本身來創建,使用spring後,程序變爲被動接收spring創建好的對象。

控制反轉別名依賴注入(dependency injection)

IOC是一種編程思想,由主動編程變爲被動接收,IOC是實現是通過IOC容器來實現的,IOC容器—BeanFactory

新建lib文件夾,導入jar包

   

Hello.java

package cn.sxt.bean;

public class Hello {
	private String name;
	public void setName(String name) {
		this.name = name;
	}
	public void show() {
		System.out.println("hello,"+name);
	}
}

Test.java

package cn.sxt.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.sxt.bean.Hello;

public class Test {
	public static void main(String[] args) {
		//解析beans.xml文件生成管理相應的bean對象
		ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
	context.getBean("hello");
	Hello hello=(Hello)context.getBean("hello");
	hello.show();
	}
}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<!-- bean就是Java對象 由spring容器來創建和管理 -->
<bean name="hello" class="cn.sxt.bean.Hello">
	<property name="name" value="張三"/>
</bean>
</beans>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章