Spring基础配置实现HelloWorld操作步骤

操作步骤:
1.导入Spring的jar包及commons-logging.jar
2.在src下创建相应的beans.xml
3.为bean.xml添加 Schema
	<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">
	</beans>
4.创建对象,新建一个类
5.在beans.xml中创建对象
 	<!-- 创建如下bean等与完成了 HelloWorld helloWorld=new HelloWorld() -->
	<bean id="helloWorld" class="com.spring.model.HelloWorld"/>       
6.在测试类中使用这个对象 	 	
	 6.1、创建Spring工厂
		private BeanFactory beanFactory=new ClassPathXmlApplicationContext("beans.xml");
	 6.2//通过工厂获取Spring的对象
		//此处getBean中的helloWorld 就是beans.xml中的id
		HelloWorld hello1=(HelloWorld)beanFactory.getBean("helloWorld");
		HelloWorld hello2=beanFactory.getBean("helloWorld",HelloWorld.class);
		//此时的hello1对象就是被Spring管理的对象
		System.out.println(hello1.hello());
	6.3//如果在bean中没有做scope的配置,默认是(singleton)单例
		System.out.println(hello1==hello2);
	
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等与完成了 HelloWorld helloWorld=new HelloWorld() -->
	<bean id="helloWorld" class="com.spring.model.HelloWorld" scope="prototype"/>
	
</beans>

HelloWorld.java
package com.spring.model;

public class HelloWorld {
	public String hello(){
		System.out.println();
		return "hello world";
	}
	
}

TestSpring
package com.spring.test;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.HelloWorld;

public class TestSpring {
	//创建Spring工厂
	private BeanFactory beanFactory=new ClassPathXmlApplicationContext("beans.xml");
	
	@Test
	public void testHello(){
		//通过工厂获取Spring的对象
		//此处getBean中的helloWorld 就是beans.xml中的id
		HelloWorld hello1=(HelloWorld)beanFactory.getBean("helloWorld");
		HelloWorld hello2=beanFactory.getBean("helloWorld",HelloWorld.class);
		//此时的hello1对象就是被Spring管理的对象
		System.out.println(hello1.hello());
		
		//如果在bean中没有做scope的配置,默认是(singleton)单例
		System.out.println(hello1==hello2);
		
	}
}

运行结果
hello world
false



你可能感兴趣的:(spring,spring基础)