IOC,控制反转,从最浅显的角度来说就是经过Spring容器来负责建立对象html
大致的实现结构java
1.首先有一个咱们须要运行的类spring
2.在spring专属的xml配置文件中配置该类app
3.启动容器 xml
4.从该容器中获取此类的对象htm
5.调用对象的方法对象
简单demoblog
1.导包,最基本的是spring.jar和commons-logging.jarget
2.建立咱们须要运行的类io
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(){ /* * 一、启动spring容器 * 二、从spring容器中把helloWorld拿出来 * 三、对象.方法 */ //启动spring容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//配置文件的全路径 HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");//根据配置文件中的id获取对象 helloWorld.hello(); } }