本人是一枚小菜一枚,刚刚踏入学习Spring 框架的进程中,为了记录每天学习到的知识点,加强记忆,所以在这里以日志的方式来记录每天学到的分散的知识。接来下,就是正题了:
1.IOC控制反转
所谓IOC控制反转,就是指原来我们创建一个类的时候,都是需要我们来new一个对象,而IOC控制反转就是将这个创建对象实例的权利交给来Spring,由Spring来生成。
2.IOC的编程实现
主要是四个步骤:
1.导入jar包
导入jar包在这里主要是四个核心+1个依赖。分别如下:
其中com.springsource.org.apache.commons.logging-1.1.1.jar就是一个依赖,而spring-beans,spring-context,spring-core,spring-expression就是四个核心。它们都是spring框架中的core contain。在WEB-INF中的lib导入了相关的包之后,就是要为它们建立路径。
2.创建目标类
这里的目标类就是指的就是要由spring来代理生成的实体类。在这里我们使用MessageService.interface和MessageServiceImp.java两个,这里主要由spring代理的是MessageServiceImp实体类。具体代码如下:
MessageService.interface
public interface MessageService{
public abstract printMessage(String message);
}
MessageServiceImp.java public class MessageServiceImp implements MessageService{ public abstract printMessage(String message){ System.out.println(message); }
MessageService messageService=(MessageService) applicationContext.getBean("MessageServiceImpId"); messageService.printMessage("IOC is so easy");
}
3.创建配置文件
涉及到配置文件的创建,在这里就设计到两个问题,配置文件的位置和配置文件的名称。配置文件的位置就是在classpath中,也就是src目录下。配置文件的名称可以是任意的,但这里为了适应大家的开发习惯,我们使用applicationContext.xml。而编写的内容我们在这里采用的scheme约束。代码如下:
<?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="MessageServiceImpId" class="MessageServiceImp"></bean>
</beans>
这里我们主要是通过<bean>标签来进行来配置,bean中id是要从Spring框架中拿到实例的名称,而class是真正的实体类的位置,这里一般采用的是相对路径,因为它们都是在src下面。我这里目录结构如下:
4.测试
主要是两个部分:获取Spring容器和通过Spring容器来创建Bean
1.获取Spring容器的代码如下:
String xmlPath="applicationContext.xml";
ApplicatioConext applicationContext=new ClassPathXMlApplicationContext(xmlPath);
2.通过spring容器来获取实体类
MessageService messageService=(MessageService) applicationContext.getBean("MessageServiceImpId");
messageService.printMessage("IOC is so easy");
好了就是跑一下了,主要通过@Test junit来实现。