spring剖析

[TOC]

IOC

IoC(Inverse of Control:控制反转)是一种设计思想,就是 将原本在程序中手动创建对象的控制权,交由Spring框架来管理。 IoC 在其他语言中也有应用,并非 Spring 特有。 IoC 容器是 Spring 用来实现 IoC 的载体, IoC 容器实际上就是个Map(key,value),Map 中存放的是各种对象。

Spring IoC的初始化过程

  • 如果要使用Spring实现控制反转,需要先在src/main/resources下创建一个名为spring.xml的XML配置文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?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">

    <!-- 将Student交给spring容器 -->
    <bean id="student" class="com.sjh.entity.Student">
    <property name="id" value="1"/>
    <property name="name" value="sjh"/>
    <property name="age" value="24"/>
    </bean>

    </beans>
  • 利用IoC获取对象(通过bean的id):

    ClassPathXmlApplicationContext获取了配置文件,通过配置文件对象的getBean方法获取一个Student的实例,由于在配置文件中已经注入了属性,此时student是有相关属性的。

    1
    2
    3
    4
    5
    6
    @Test
    public void testIoC2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
    Student student = (Student) ac.getBean("student");
    System.out.println(student);
    }

AOP

AOP(Aspect-Oriented Programming:面向切面编程)能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码降低模块间的耦合度,并有利于未来的可拓展性和可维护性

Spring AOP就是基于动态代理的,如果要代理的对象,实现了某个接口,那么Spring AOP会使用JDK Proxy,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用Cglib ,这时候Spring AOP会使用 Cglib 生成一个被代理对象的子类来作为代理,如下图所示: