一.IOC
1.什么是IOC的功能?
IoC – Inverse of Control,控制反转,将对象的创建权反转给Spring!!
使用IOC可以解决的程序耦合性高的问题!!
2.demo搭建(以java项目,spring 4.2.4为例)
spring搭建需要以下包
核心包:spring-beans-4.2.4.RELEASE.jar,spring-context-4.2.4.RELEASE.jar,spring-core-4.2.4.RELEASE.jar,spring-expression-4.2.4.RELEASE.jar
日志包:com.springsource.org.apache.commons.logging-1.1.1.jar 日志规范
com.springsource.org.apache.log4j-1.2.15.jar 日志实现
同时日志还需要log4j.properties 配置文件
然后在src下创建spring配置文件 applicationContext.xml 内容为
<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl"></bean>
<bean id="customerDao" class="com.itheima.dao.impl.ICustomerDaoImpl"></bean>
然后在代码里面写
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerService customerService = (CustomerService) ac.getBean("customerService");
ICustomerDaoImpl customerDao = (ICustomerDaoImpl) ac.getBean("customerDao");
System.out.println(customerService);
System.out.println(customerDao);
注意:当代码中new 多个ClassPathXmlApplicationContext(“applicationContext.xml”)会创建多个工厂
ApplicationContext ac1 = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1 = (UserService) ac1.getBean("userService");
userService1.add();
ApplicationContext ac2 = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService2 = (UserService) ac2.getBean("userService");
userService2.add();
System.out.println(userService1);
System.out.println(userService2);
输出:
com.gyf.service.impl.UserServiceImpl@15ff3e9e
com.gyf.service.impl.UserServiceImpl@5fdcaa40
3.延迟创建bean与立即创建bean
由ApplicationContext可知,还有其他类实现了BeanFactory接口
如:XmlBeanFactory(已经不推荐使用了)
ClassPathXmlApplicationContext和XmlBeanFactory区别:
ClassPathXmlApplicationContext 实现了ApplicationContext接口,提供的是一种立即加载思想来创建bean对象。只要配置文件一解析完,就立即创建bean对象
XmlBeanFactory 实现了BeanFactory接口,提供的是一种延迟加载思想来创建bean对象。bean对象什么时候用什么时候来创建
4.Bean的三种创建方式
1.默认调用无参构造函数创建,如果类中没有默认无参构造函数,则创建失败,报异常
2.使用静态工厂中的方法创建对象,需要使用bean标签的factory-method属性,指定静态工厂中创建对象的方法
eg:
<bean id="staticCustomerService" class="com.itheima.factory.StaticFactory" factory-method="getCustomerService"></bean>
public class StaticFactory {
public static CustomerService getCustomerService(){
return new CustomerServiceImpl();
}
}
3.使用实例工厂中的方法创建
eg:
<!-- 创建实例工厂 -->
<bean id="instanceFactory" class="com.itheima.factory.InstanceFactory"></bean>
<!-- 创建实例,通过属性factory-bean指定工厂,通过factory-method指定由工厂类中哪个方法创建实例 -->
<bean id="instanceCustomerService" factory-bean="instanceFactory" factory-method="getCustomerService"></bean>
5.bean的作用范围
如果是单例对象,作用范围是整个应用
如果是多例对象,作用范围是一次使用过程中
可以通过配置的方式来调整作用范围,配置bean标签的scope属性
属性的取值:
1.singleton:在spring Ioc 容器中仅存在一个Bean实例,Bean以单例方式存在(默认值)
2.prototype:每次从容器中调用Bean时,返回一个新的实例,相当于执行 new XxxBean()```
6.bean的生命周期
单例:
出生:容器创建,对象就出生
活着:只要容器在,对象就一直存在
销毁:容器销毁,对象销毁
多例:
出生:每次使用时,创建对象
活着:只要对象在使用中,就一直活着
销毁:当对象长时间不使用,并且也没有别的对象引用时,由java的垃圾回收器回收
涉及bean标签的两个属性:
init-method 这个属性用来指定 bean对象创建时执行什么方法
destroy-method 这个属性用来指定 bean对象销毁时执行什么方法