您的位置:首页 > 编程语言 > Java开发

SpringIOC_HelloWord

2015-11-01 16:46 344 查看
Spring的控制反转:把对象的创建、初始化、销毁等工作交给spring容器来做。由spring容器控制对象的生命周期。

步骤:

创建java project 加入jar包

spring.jar --spring的核心类库
commons-logging --日志包

1.创建测试类 HelloWord

package com.spring.createobject;

public class HelloWord {

public void hello(){
System.out.println("hello word!");
}

}


2.创建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-2.5.xsd"> <!--
把一个类放入到spring容器中,该类就称为bean
描述一个类
id 唯一标示
class 类名
-->
<bean id="helloWorld" class="com.spring.createobject.HelloWord"></bean>
</beans>


3.测试

  

package com.spring.createobject.test;

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

import com.spring.createobject.HelloWord;

public class HelloWordTest {

@Test
public void testHelloWord(){

//启动Spring容器
ApplicationContext context=
new ClassPathXmlApplicationContext("applicationContext.xml");

//根据id把Spring容器中的bean提取出来
HelloWord helloWord = (HelloWord) context.getBean("helloWorld");

helloWord.hello();

}

}


打印结果:

hello word!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: