一. 环境搭建
1. 安装jdk
2. 安装maven
3. 下载Spring Tool Suite 3.7.0: https://spring.io/tools/sts/all 或者安装其插件
二. helloworld: 演示IOC
1. 创建一个maven项目
2. 引入依赖
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> </dependencies>
3. 创建类:
package com.spring.bean; public class HelloWorld { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void hello(){ System.out.println("hello " + this.name); } @Override public String toString() { return "HelloWorld [name=" + name + "]"; } }
4. 创建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.xsd"> <bean id="helloWorld" class="com.spring.bean.HelloWorld"> <property name="name" value="Spring"></property> </bean> </beans>
5.创建运行类
package com.spring.bean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1. 创建Spring 的IOC容器对象 //ApplicationContext 代表IOC对象 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.从IOC容器中取出bean实例 //利用id定位到IOC容器中的bean HelloWorld hello = (HelloWorld) ctx.getBean("helloWorld"); //3, 调用hello方法 hello.hello(); //利用类型定位到IOC容器中的bean,如果applicationConfig.xml里配制多个HelloWorld的bean,bean不唯一,会出错 HelloWorld hello1 = ctx.getBean(HelloWorld.class); System.out.println(hello1 == hello); } }
6.运行main类
得到结果:
十二月 26, 2015 9:34:14 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2e0fa5d3: startup date [Sat Dec 26 09:34:14 CST 2015]; root of context hierarchy 十二月 26, 2015 9:34:14 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] hello Spring true
成功。