Spring快速入門示例

開發環境:

Spring 4.0.0+Myeclipse10+JDK1.7

開發過程:

1、新建一個spring01的java工程,在工程目錄下新建一個lib包(或者直接建一個web工程,兩個方法均可),將以下包導入到lib中


2、創建com.at.beans包,在包中創建HelloWorld.java類。
package com.at.beans;

public class HelloWorld {

	private String name;

	public void setName(String name) {
		this.name = name;
	}
	
	public void hello(){
		System.out.println("name " + name);
	}
}

3、在src文件夾下面新建一個applicationContext.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-4.0.xsd">

	<!-- 這裏的class是使用反射創建的類對象,相當於HelloWorld helloWorld = new HelloWorld(); -->
	<bean id="helloWorld" class="com.at.beans.HelloWorld">
		<property name="name" value="spring"></property>
	</bean>

</beans>

4、測試運行結果代碼。
package com.at.beans;

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

public class TestHelloWorld {

	public static void main(String[] args) {
		
		//1、創建spring的IOC容器對象
		ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
		
		//2、從IOC容器中獲取bean實例
		HelloWorld helloWorld=(HelloWorld)context.getBean("helloWorld");
		
		//3、調用方法
		helloWorld.hello();
	}
}

5、程序運行結果輸出。
五月 17, 2017 4:19:32 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5a874bd3: startup date [Wed May 17 16:19:32 CST 2017]; root of context hierarchy
五月 17, 2017 4:19:32 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
name spring


By luoyepiaoxue2014
微博地址: http://weibo.com/luoyepiaoxue2014 點擊打開鏈接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章