SpringIOC_HelloWord
2015-11-01 16:46
344 查看
Spring的控制反转:把对象的创建、初始化、销毁等工作交给spring容器来做。由spring容器控制对象的生命周期。
步骤:
创建java project 加入jar包
spring.jar --spring的核心类库
commons-logging --日志包
1.创建测试类 HelloWord
2.创建ApplicationContext.xml:
3.测试
打印结果:
步骤:
创建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!
相关文章推荐
- spring boot实战(第十二篇)整合RabbitMQ
- spring的Bean注入和P标签使用
- eclipse 快捷键
- Java中getResourceAsStream的用法
- 即将改变软件开发的5个Java9新特性
- Java 自定义注解例子
- java学习:Graphics绘制基本图形对象
- java基础测试(2)
- spring Bean的作用域、生命周期和后处理器
- JAVA集合类
- struts2 中 Actionsupport 的作用
- java中static关键字
- struts中使用this.addFieldError时出现错误解决办法
- 字节码操作库Javassist
- springMVC aop
- java synchronized详解
- spring 与设计模式(创建型)之Builder模式
- java 为什么wait(),notify(),notifyAll()必须在同步方法/代码块中调用?
- Spring读取properties文件内容
- Gradle新手之路01_安装Gradle