1、创建一个maven项目
选择quickstart版本,这里还用不到web所以用这个就足够了
2、创建好工程后,引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
这里只是使用springIOC功能,所以引入spring-context依赖就可以了。
spring-context就是给 Spring 提供一个运行时的环境,用以保存各个对象的状态,其实就是spring容器,引入这个依赖会同时引入其所依赖的其他基础依赖,如spring-core和spring-bean等。
3、创建一个HelloWorld类
package com.imooc.spring;
public class HelloWorld {
private String name;
public void setName(String name){
this.name = name;
}
public void sayHello(){
System.out.println("HellowWorld,我的名字是 : "+ name);
}
}
4、配置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.xsd">
<bean id="helloWorld" class="com.imooc.spring.HelloWorld">
<property name="name" value="YellowStar"></property>
</bean>
</beans>
5、测试类
package com.imooc.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test1 {
public static void main(String[] args) {
//创建spring的IOC容器对象
//Application是spring中的接口
//ClassPathXmlApplicationContext,可以获取src下的applicationContext.xml文件
ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) ct.getBean("helloWorld");
helloWorld.sayHello();
}
}
6、输出结果
解释:
新建了一个HelloWorld类,里面有个属性name和setName方法
在配置文件applicationContext.xml中创建了HelloWorld类的bean,并且为其name属性赋了值:
<property name="name" value="YellowStar"></property>
还可以用这种方式赋值:
<property name="name">
<value>YellowStar</value>
</property>
在测试类中:
首先获取spring容器上下文环境
ApplicationContext ct = new ClassPathXmlApplicationContext(“applicationContext.xml”);
然后从里面取出helloWorld这个bean:
HelloWorld helloWorld = (HelloWorld) ct.getBean(“helloWorld”);
然后就可以使用了。