1.创建bean的对象方式
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建bean的三种方式
1.使用默认构造函数创建对象(不要写有参构造函数)在spring的配置文件中使用bean标签 配置 id和class属性之后,且没有其他属性和标签时 采用的就是默认构造函数创建bean队形 此时如果类中没有默认构造函数 则对象无法创建
-->
<bean id="idao" class="comm.dao.impl.DaoImpl"></bean>
<bean id="iservice" class="comm.service.impl.AccountServiceImpl"></bean>
<!--
2.使用普通工厂中的方法创建对象 (使用某个类中的方法创建对象 并存入spring容器
-->
<bean id="idao" class="comm.dao.impl.DaoImpl"></bean>
<bean id="beanfact" class="comm.factory.ServiceFactory"></bean>
<bean id="iservice" factory-bean="beanfact" factory-method="test"></bean>
<!--
3.使用工厂中的静态方法创建对象 (使用某个类中的静态方法创建对象 并存入spring容器
-->
<bean id="idao" class="comm.dao.impl.DaoImpl"></bean>
<bean id="iservice" class="comm.factory.ServiceFactory" factory-method="test"></bean>
<!--
bean的作用范围调整
bean标签的sope属性:
作用:用于指定bean的作用范围
取值:
singleton 单例
prototype多例对象
request 作用于web应用的请求范围
session 作用于web应用的回话范围
globalsession用于集群环境的会话范围
bean 对象的生命周期:
单例对象:
当容器创建时对象出生 (单例对象的生命周期和容器的生命周求一样
多例对象:
当使用对象时 Spring对象为我们创建对象, 当对象长时间不用且不被别的对象引用时 由java回收机制收取
依赖注入方式:
1.set方法注入 baen标签中name对应的是 set方法名(SetUserName -》 username)
2.构造函数注入 有参构造函数 <constructor-arg></constructor-arg>
3.
-->
</beans>
2.Spring容器的加载方式以及 Benfactory 和ApplicationContext的different
/**
*ApplicationContext三种加载方式:
* ClassPathXmlApplicationContext 在类路径下加载
* FileSystemXmlApplicationContext 在磁盘任意路径下加载
* AnnotationConfigApplicationContext 使用注解的方式
*ApplicationContext的区别:
* BeanFactory是spring核心容器的顶级实现类
* 1.ApplicationContext (立即加载策略) 加载文件的时候就创建bean对象 (适用单例对象)
* 2.benafactory 创建核心容器是延迟加载策略 当使用的对象的时候才创建对象 (适用多例对象适用)
* 3.benafactory是顶层接口.
*
*
* */
// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
// FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("D:\\Download\\IOC\\src\\main\\resources\\bean.xml");
// 使用BeanFactory延迟加载对象
ClassPathResource classPathResource = new ClassPathResource("bean.xml");
XmlBeanFactory context = new XmlBeanFactory(classPathResource);
IDao idao =(IDao) context.getBean("idao", IDao.class);
AccountServiceImpl service =(AccountServiceImpl) context.getBean("iservice", IAccountService.class);
System.out.println(idao);
System.out.println(service);
service.setiDao(idao);
service.saveAccount();