work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

MyEclipse Spring 学习总结一 Spring IOC容器

Posted on 2016-02-02 11:22  work hard work smart  阅读(454)  评论(0编辑  收藏  举报

一、Spring IOC容器---- Spring AllicationContext容器

程序的结构如下:

1.首先在MyEclipse 创建创建Java Project

2.创建好后,添加sping支持。在project上右击, MyEclipse->Add spring Capabilities.

3.之后会自动生成applicationContent.xml文件

 1)创建HelloWorld.java

public class HelloWorld {

	private String message;
	   public void setMessage(String message){
	      this.message  = message;
	   }
	   public void getMessage(){
	      System.out.println("Your Message : " + message);
	   }
}

2)创建MainApp.java

public class MainApp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		HelloWorld obj = (HelloWorld)context.getBean("helloWorld");
		obj.getMessage();

	}

}

 3)在applicationContent.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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="helloWorld" class="bu.example.com.HelloWorld">
		<property name="message" value="Hello World!!!" />
	</bean>
</beans>

4.最后运行,结果如下:

  

 

 二、Spring IOC容器---- Spring BeanFactory容器

只需修改MainApp.java文件

public static void main(String[] args) {
		XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		HelloWorld obj = (HelloWorld)factory.getBean("helloWorld");
		obj.getMessage();

	}

 两个输出的效果是一样的。 

 

1.spring jar包下载地址

spring官网的改变,导致找不到下载地址:

spring framework download site

http://maven.springframework.org/release/org/springframework/spring/

(参考)

2. spring教程 参考 使用Eclipse IDE