IOC,控制反转,从最浅显的角度来讲就是通过Spring容器来负责创建对象
大体的实现结构
1.首先有一个我们需要运行的类
2.在spring专属的xml配置文件中配置该类
3.启动容器
4.从该容器中获取此类的对象
5.调用对象的方法
简单demo
1.导包,最基本的是spring.jar和commons-logging.jar
2.创建我们需要运行的类
public class HelloWorld {
public void hello(){
System.out.println("hello world");
}
}
3.编写applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--beans里面的每个bean就是一个需要容器启动的类 -->
<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">
<!--每个bean的id一般都命名为该类名的首字母小写的名字-->
<bean id="helloWorld" class="HelloWorld的全类名"></bean>
<!--每一个alias都是一个别名,name就是上面定义的id,alias就是别名-->
<alias name="helloWorld" alias="王五"/>
<alias name="helloWorld" alias="林志玲"/>
<alias name="helloWorld" alias="赵六"/>
</beans>
4.启动容器,获取对象,调用方法
public class HelloWorldTest {
@Test
public void test(){
/*
* 1、启动spring容器
* 2、从spring容器中把helloWorld拿出来
* 3、对象.方法
*/
//启动spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//配置文件的全路径
HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根据配置文件中的id获取对象
helloWorld.hello();
}
}