对spring的理解:
spring就是一个容器,用来生成bean。spring的核心容器是benas。core。context(配置文件) ,expression。
IOC即:控制反转,
在没有IOC之前,直接new一个对象。会导致工作很麻烦。
由Spring创建对象实例——>IOC控制反转,创建实例由spring完成
IOC做法:从spring工厂(容器)中获得,需要将实现类的全限定名称配置到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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置service
<bean>需要配置的对象
id:用于之后从spring容器中获得实例时使用的
class:需要创建实例的全限定类名
-->
<bean id="userServiceId" class="com.xiewanru.IOC.UserServiceImpl"></bean>
在xml配置中,告诉spring容器,需要实例化的是哪个接口实现类,然后我们根据id取出bean。就能获得一个实例:
public static void main(String[]args){
String xmlPath="beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//原来的办法
// UserServices userServices = new UserServiceImpl();
// userServices.addUser();
//现在的
UserServices userServices = (UserServices)applicationContext.getBean("userServiceId");
userServices.addUser();
这样就能得到一个实例了。这只是最简单的,之后又不断的进化。IOC只是一种思想,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系