概述
- 解释:是一个全栈式(full-stack)的轻量级开源框架
- 内核:
- IoC(Inverse Of Control:反转控制)
- AOP(Aspect Oriented Programming:面向切面编程)
解耦
- 思路:
- 使用反射来创建对象,而避免使用new关键字(减少类之间依赖)
- 通过读取配置文件来获取要创建的对象全限定类名
- 方法:
- 工厂模式解耦。利用上述思路来写工厂类,达到类中通过反射机制创建对象的操作。
IOC(反转控制)
- 功能:
- 削减计算机程序的耦合(解除我们代码中的依赖关系)
- 两种创建对象方式
private IAccountDao accountDao = new AccountDaoImpl();
private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
- 解释:
- 第一种方式:控制权在当前类手里
- 第二种方式:将创建权给工厂类(框架)
Spring实现
- 创建配置文件(Bean.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">
<!-- 把对象的创建交给Spring管理-->
<bean id="accountService" class="com.learnspring.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.learnspring.dao.impl.AccountDaoImpl"></bean>
</beans>
-
使用以及问题
-
ApplicationContext的三个常用实现类:
- ClassPathXXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在就加载不了
- FileSystemXmlApplicationContext:可以加载磁盘任意路径的配置文件(必须有访问权限)
- AnnotationConfigApplicationContext:用于读取注解创建容器的
-
核心容器的两个接口引发出的问题:
容器名 解释 使用场景 ApplicationContext 在创建核心容器时,创建对象采取的策略是采用立即加载的方式。一读取完配置文件马上就创建配置文件中配置的对象。 单例对象 BeanFactory 创建核心容器时,创建对象采取的策略是采用延迟加载的方式。什么时候根据id获取对象,什么时候才真正的创建对象。 多例对象 -
示例代码
public class Client { /** * 获取spring的Ioc核心容器,并根据ID获取对象 * @param args */ public static void main(String[] args){ //获取核心容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //根据ID获取Bean对象 AccountService as = (AccountService) ac.getBean("accountService"); //进行强转 AccountDao adao = ac.getBean("accountDao",AccountDao.class); //传入字节码,不用强转 System.out.println(as); System.out.println(adao); } }
-
创建Bean的三种方式
- 第一种:
- 在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="com.learnspring.service.impl.AccountServiceImpl"></bean>
- 第二种:
- 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
<bean id="instanceFactroy" class="com.learnspring.factory.InstanceFactory"></bean> //工厂类,用于获得accountService
<bean id="accountService" factory-bean="instanceFactroy" factory-metho