创建一个Spring的HelloWorld程序

Spring IOC

IOC指的是控制反转,把对象的创建、初始化、销毁等工作都交给Spring容器。由spring容器来控制对象的生命周期。下图能够说明我们传统创建类的方式和使用Spring之后的差别:

创建Java类:

package com.yihai.springioc;


//IOC指的是控制反转。把对象的创建、初始化、销毁等工作都
//交给Spring容器。由spring容器来控制对象的生命周期。
public class HelloWorld {
	public void hello(){
		System.out.println("hello world");
	}
}

把该类放在spring容器中:

<?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-2.5.xsd"> <!-- 表示一个类id是累类的唯一标示,class代表类的全名,也就是包名+类名 --> <bean id="helloWorld" class="com.yihai.springioc.HelloWorld"> </bean> </beans>


从spring容器中取出类的对象

package com.yihai.springioc;

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

//IOC指的是控制反转。把对象的创建、初始化、销毁等工作都
//交给Spring容器。

由spring容器来控制对象的生命周期。 public class HelloWorld { public void hello(){ System.out.println("hello world"); } public static void main(String[] args) { /** * 1、启动spring容器 * 2、从spring容器中把该对象提取出来 * 3、对象调用方法 */ ApplicationContext context = new ClassPathXmlApplicationContext("beanioc.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); helloWorld.hello(); } }


这类创建bean对象是spring调用类的默认的构造方法来创建对象。另外2中创建对象的方式是使用静态工厂方法创建Bean使用实例工厂方法创建Bean。

原文地址:https://www.cnblogs.com/blfbuaa/p/6918188.html