Spring是一个非常活跃的开源框架;它是一个基于Core来构架多层JavaEE系统的框架,它的主要目的是简化企业开发。
理论:
控制反转:控制反转——Spring通过一种称作控制反转(IoC)的技术促进了低耦合。当应用了IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。你可以认为IoC与JNDI相反——不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。
Spring的控制反转:把对象的创建、初始化、销毁等工作交给Spring容器来做。由spring来口控制对象的声明周期。
不用spring情况下:
spring控制反转:
实践:
扫描二维码关注公众号,回复:
1042603 查看本文章
步骤:
一、下载Spring的jar包
二、环境配置
1、新建一个java项目——新建一个lib文件夹——将spring.jar包,commons-logging.jar包放进去
然后右击spring.jar(还有logging.jar)——BuildPath——Add to Build Path
最终环境配置结果:
2、导入Junit4
三、编写代码
新建如下东西
HelloWorld.java中:
package cn.itcast.springtest.ioc; public class HelloWorld { public void say(){ System.out.println("hello,我是牛千千"); } }
Spring配置文件: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"> <!-- 把HelloWorld这个类 纳入spring容器中 id为bean的唯一标识 正规写法: 类的第一个字母变成小写,其余不变 class为类的全名 --> <bean id="helloWorld" class="cn.itcast.springtest.ioc.HelloWorld"></bean> </beans>
IOCTest.java
package cn.itcast.springtest.ioc; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* * 控制反转IOC * 牛千千 */ public class IOCTest { /* * 启动spring容器 * 创建spring容器对象就相当于启动了spring容器 */ @Test public void testHelloWorld(){ ApplicationContext context =new ClassPathXmlApplicationContext("cn/itcast/springtest/ioc/applicationContext.xml"); HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); helloWorld.say(); } }
运行一下即可:
运行成功。