系列文章:Spring:IoC、AOP 与事务 的第 2 篇。
Spring AOP
AOP(Aspect-Oriented Programming:⾯向切⾯编程)能够将那些与业务⽆关,却为业务模块所共同调⽤的逻辑或责任(例如事务处理、⽇志管理、权限控制等)封装起来,便于减少系统的重复代码,降低模块间的耦合度,并有利于未来的可拓展性和可维护性。
- Spring AOP就是基于动态代理的,如果要代理的对象,实现了某个接⼝,那么Spring AOP会使⽤JDK Proxy,去创建代理对象,⽽对于没有实现接⼝的对象,就⽆法使⽤ JDK Proxy 去进⾏代理了,这时候Spring AOP会使⽤Cglib ,这时候Spring AOP会使⽤ Cglib ⽣成⼀个被代理对象的⼦类来作为代理。

- Spring Aop是运行时增强。
- Cglib Aop是编译器增强。
AOP专门用于处理系统中分布于各个模块中交叉关注点的问题,在JavaEE应用中,常常通过AOP来处理一些横切性质的系统级服务,如事物管理、安全检查、缓存对象池管理。
- 1.)切面 -Aspect 切面类 比如日志类
- 2.) 连接点 - Join Point 加入切点的那个点
- 3.)通知 -Advice 是在切面某个特定的连接点上的动作。
- 4.)切入点 - Point Cut 匹配连接点的断点
- 5.)引入 - Introduction
- 6.)目标对象 - Target Object 被一个或多个通知对象,永远被代理的对象。
- 7.) AOP代理 - AOP Proxy AOP创建的对象用来实现切面对象。
- 8.)织入 - Weaving
- 9.)AOP通俗的理解:
一个组建A,不关心其他常用的服务组件B,但是这个组件A使用组件B的时候不是组建A自身去调用,而是通过配置等其他方式,比如Spring中可以通过XML配置文件。这样就使的A压根不需要知道服务组件B是怎么样的,A只关心自己的业务逻辑,具体A使用B的时候,配置文件去做,与具体的A组件无关。
Spring框架中的设计模式
- 工厂模式:BeanFactory就是简单工厂模式的体现,用来创建对象的实例
- 单例模式:Bean默认为单例模式
- 代理模式:Spring的AOP功能用到了JDK的动态代理和CGLIB字节码生成技术
- 模板方法:用来解决代码重复的问题。比如. RestTemplate, JmsTemplate, JpaTemplate
- 观察者模式:定义对象键一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知被制动更新,如Spring中listener的实现--ApplicationListener,Spring 事件驱动模型就是观察者模式很经典的⼀个应⽤。
- 适配器模式 :Spring AOP 的增强或通知(Advice)使⽤到了适配器模式、spring MVC 中也是⽤到了适配器模式适配 Controller 。
- 策略模式: Bean的实例化的时候决定采用何种方式初始化bean实例(反射或者CGLIB动态字节码生成),Resource 接口是具体资源访问策略的抽象。
- 装饰器模式:Spring中用到的包装器模式在类名上有两种表现:一种是类名中含有Wrapper,另一种是类名中含有Decorator。
- 模版模式:Spring Template 都采用了该模式。
Bean注册方式
- XML 配置文件的注册方式
<bean id="person" class="org.springframework.beans.Person">
<property name="id" value="1"/>
<property name="name" value="Java"/>
</bean>
Java 注解的注册方式
// 可以使用 @Component 注解方式来注册 Bean
@Component
public class Person {
private Integer id;
private String name
// 忽略其他方法
}
// @Bean 注解方式来注册 Bean
@Configuration
public class Person {
@Bean
public Person person(){
return new Person();
}
// 忽略其他方法
}
Java API 的注册方式
// 使用 BeanDefinitionRegistry.registerBeanDefinition() 方法的方式注册 Bean
public class CustomBeanDefinitionRegistry implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
RootBeanDefinition personBean = new RootBeanDefinition(Person.class);
// 新增 Bean
registry.registerBeanDefinition("person", personBean);
}
}
Spring Bean 的作用域
Singleton Bean 无论是依赖查找还是依赖注入,均为同一个对象。
Singleton Bean 只是在当前容器内是一位,存在多个容器的时候,每个容器可以存储一份对象。
Prototype Bean 无论是依赖查找还是依赖注入,均为新生成对象。
- singleton
- 表示在 Spring 容器中只有一个 Bean 实例,以单例的形式存在,是默认的 Bean 作用域。
- prototype
- 原型作用域,每次调用 Bean 时都会创建一个新实例,也就是说每次调用 getBean() 方法时,相当于执行了 new Bean()。
- 扩展
request
- 每次 Http 请求时都会创建一个新的 Bean,该作用域仅适应于 WebApplicationContext 环境。
session
- 同一个 Http Session 共享一个 Bean 对象,不同的 Session 拥有不同的 Bean 对象,仅适用于 WebApplicationContext 环境。
global session
- 全局session共享一个bean对象。
application
- 全局的 Web 作用域,类似于 Servlet 中的 Application。
webSocket
Spring 中的单例 bean 的线程安全问题
- 单例 bean 存在线程问题,主要是因为当多个线程操作同⼀个对象的时候,对这个对象的⾮静态成员变量的写操作会存在线程安全问题。在类中定义⼀个ThreadLocal成员变量,将需要的可变成员变量保存在 ThreadLocal 中(推荐的⼀种⽅式)。
Bean 生命周期
- 对于 Spring Bean 来说,并不是启动阶段就会触发 Bean 的实例化,只有当客户端通过显式或者隐式的方式调用 BeanFactory 的 getBean() 方法时,它才会触发该类的实例化方法。当然对于 BeanFactory 来说,也不是所有的 getBean() 方法都会实例化 Bean 对象,例如作用域为 singleton 时,只会在第一次,实例化该 Bean 对象,之后会直接返回该对象。但如果使用的是ApplicationContext 容器,则会在该容器启动的时候,立即调用注册到该容器所有 Bean 的实例化方法。getBean() 方法是属于 BeanFactory 接口的,它的真正实现是AbstractAutowireCapableBeanFactory 的 createBean() 方法,而 createBean() 是通过 doCreateBean() 来实现的,具体源码实现。

- 实例化Bean
- 对于BeanFactory容器,当客户向容器请求一个尚未初始化的bean时,或初始化bean的时候需要注入另一个尚未初始化的依赖时,容器就会调用createBean进行实例化。对于ApplicationContext容器,当容器启动结束后,通过获取BeanDefifinition对象中的信息,实例化所有的bean。
- 设置对象属性(依赖注入)
- 实例化后的对象被封装在BeanWrapper对象中,紧接着,Spring根据BeanDefifinition中的信息 以及 通过BeanWrapper提供的设置属性的接口完成依赖注入。
- 处理Aware接口
- 接着,Spring会检测该对象是否实现了xxxAware接口,并将相关的xxxAware实例注入给Bean。
- 如果这个Bean已经实现了BeanNameAware接口,会调用它实现的setBeanName(String beanId)方法,此处传递的就是Spring配置文件中Bean的id值。
- 如果这个Bean已经实现了BeanFactoryAware接口,会调用它实现的setBeanFactory()方法,传递的是Spring工厂自身。
- 如果这个Bean已经实现了ApplicationContextAware接口,会调用setApplicationContext(ApplicationContext)方法,传入Spring上下文。
- 接着,Spring会检测该对象是否实现了xxxAware接口,并将相关的xxxAware实例注入给Bean。
- BeanPostProcessor
- 如果想对Bean进行一些自定义的处理,那么可以让Bean实现了BeanPostProcessor接口,那将会调用postProcessBeforeInitialization(Object obj, String s)方法。
- InitializingBean 与 init-method
- 如果实现相关方法或者配置了 init-method则会自动调用其配置的初始化方法
- BeanPostProcessor
- 如果这个Bean实现了BeanPostProcessor接口,将会调用postProcessAfterInitialization(Object obj, String s)方法;由于这个方法是在Bean初始化结束时调用的,所以可以被应用于内存或缓存技术。
- getBean
- 可以正常使用这个bean了。
- DisposableBean
- 当Bean不再需要时,会经过清理阶段,如果Bean实现了DisposableBean这个接口,会调用其实现的destroy()方法。
- destroy-method
- 如果这个Bean的Spring配置中配置了destroy-method属性,会自动调用其配置的销毁方法。
- 精简下
- 实例化Bean: Ioc容器通过获取BeanDefinition对象中的信息进行实例化,实例化对象被包装在BeanWrapper对象中。
- 设置对象属性(DI):通过BeanWrapper提供的设置属性的接口完成属性依赖注入。
- 注入Aware接口(BeanFactoryAware, 可以用这个方式来获取其它 Bean,ApplicationContextAware):Spring会检测该对象是否实现了xxxAware接口,并将相关的xxxAware实例注入给bean。
- BeanPostProcessor:自定义的处理(分前置处理和后置处理)
- InitializingBean和init-method:执行我们自己定义的初始化方法使用
- destroy:bean的销毁
Spring配置
在 Spring Boot 中,其核心设计理念是对配置信息的管理采用约定优于配置。
Profile
Spring Boot 对配置文件的命名也做了一定的约定,分别使用 label 和 profile 概念来指定配置信息的版本以及运行环境,其中 label 表示配置版本控制信息,而 profile 则用来指定该配置文件所对应的环境。
/{application}.yml
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
- 在yaml配置文件中指定profile
spring:
profiles:
active: test
- 代码中使用
@Bean
@Profile("dev")
public DataSource devDataSource() {
//创建 dev 环境下的 DataSource
}
@Bean()
@Profile("prod")
public DataSource prodDataSource(){
//创建 prod 环境下的 DataSource
}
- 加载顺序
–file:./config/ 1
–file:./ 2
–classpath:/config/ 3
–classpath:/ 4
- 站位符
${spring.application.name} // 配置文件的信息
@spring.application.name@ // maven 打包的时候信息
Spring自动装配
SpringBoot 工程的启动类上都必须要加一个 @SpringBootApplication 注解,而且还要在 run 方法中导入我们的主类,我们就从这个被导入的主类上的注解开始分析。
- 基于添加jar依赖自动对Spring Boot程序进行配置
- spring-boot-autoconfiguration
- 开启自动装配
- @EnableAutoConfiguration
- @SpringBootApplication
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(VueBlogApplication.class, args);
}
}
SpringBootApplication
@SpringBootApplication 注解是一个复合注解。除去 Java 的 4 个元注解外,分别是 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
SpringBootConfiguration
@SpringBootConfiguration 注解本质是一个 @Configuration 注解,而 @Configuration 本质是一个 @Component 注解。
- @SpringBootConfiguration 注解的启动类,本质就是一个配置类(ConfigurationClass),此类中可以声明一个或者多个被 @Bean 注解标记的方法。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(annotation = Component.class)
String value() default "";
}
ComponentScan
执行包的扫描,如果 useDefaultFilters 属性为 true,那么它会将被 @component 注解标记以及以 @component 为元注解的注解标记的类都扫描到 IOC 容器中去。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
}
EnableAutoConfiguration
通过@Import注解将特定的类导入到容器中
- 引入AutoConfigurationImportSelector
- 读取META-INF/spring.factories
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
/**
* Return the auto-configuration class names that should be considered. By default
* this method will load candidates using {@link SpringFactoriesLoader} with
* {@link #getSpringFactoriesLoaderFactoryClass()}.
* @param metadata the source metadata
* @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
* attributes}
* @return a list of candidate configurations
*/
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
- AutoConfigurationImportSelector类中通过 SpringFactoriesLoader.loadFactoryNames() 去 classpath 下的 META-INF/spring.factories 中获取了所有需要自动装配的类,放入到了 IOC 容器中。

- 默认的信息
# Logging Systems
org.springframework.boot.logging.LoggingSystemFactory=\
org.springframework.boot.logging.logback.LogbackLoggingSystem.Factory,\
org.springframework.boot.logging.log4j2.Log4J2LoggingSystem.Factory,\
org.springframework.boot.logging.java.JavaLoggingSystem.Factory
# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader
....
Spring SPI
SPI 全称为 Service Provider Interface,是一种服务发现机制。SPI 的本质是将接口实现类的全限定名配置在文件中,并由服务加载器读取配置文件,加载实现类。
JDK中的SPI
- JDK 提供了用于服务查找的一个工具类 java.util.ServiceLoader 来实现 SPI 机制。当服务提供者提供了服务接口的一种实现之后,我们可以在 jar 包的 META-INF/services/ 目录下创建一个以服务接口命名的文件,该文件里配置着一组 Key-Value,用于指定服务接口与实现该服务接口具体实现类的映射关系。而当外部程序装配这个 jar 包时,就能通过该 jar 包 META-INF/services/ 目录中的配置文件找到具体的实现类名,并装载实例化,从而完成模块的注入。SPI 提供了一种约定,基于该约定就能很好地找到服务接口的实现类,而不需要在代码里硬编码指定。
SpringFactoriesLoader 类似这种 SPI 机制,只不过以服务接口命名的文件是放在 META-INF/spring.factories 文件夹下,对应的 Key 为 EnableAutoConfiguration。SpringFactoriesLoader 会查找所有 META-INF/spring.factories 文件夹中的配置文件,并把 Key 为 EnableAutoConfiguration 所对应的配置项通过反射实例化为配置类并加载到容器中。
- Spring 的 SPI 配置文件是一个固定的文件 -
META-INF/spring.factories,功能上和 JDK 的类似,每个接口可以有多个扩展实现,使用起来非常简单:
- Spring 的 SPI 配置文件是一个固定的文件 -
//获取所有factories文件中配置的LoggingSystemFactory
List<LoggingSystemFactory>> factories =
SpringFactoriesLoader.loadFactories(LoggingSystemFactory.class, classLoader);
自动装配注解
- @Configuration 主要编写JavaConfig类
- @Conditional 条件注解
- 类条件
- @ConditionalOnClass 包含类的时候
- @ConditionalOnMissingClass 不包含类的时候
- 属性条件
- @ConditionalOnProperty 属性条件
- Bean条件
- @ConditionalOnBean 存在某个Bean
- @ConditionalOnMissingBean 不存在某个Bean
- @ConditionalOnSingleCanditate 上下文仅存在一个Bean
- 资源类
- @ConditionalOnResource
- Web应用条件
- @ConditionalOnWebApplication 是web应用的
- @ConditionalOnNotWebApplication 非web应用的
- 其他
- @ConditionalOnExpression 表达式条件
- @ConditionalOnJava 指定不同的版本
- @ConditionalOnJndi 满足Jndi条件
- 执行顺序
- @AutoConfigureBefore 某些配置之前
- @AutoConfigureAfter 某些配置执行之后
- @AutoConfigureOrder 执行顺序
- 类条件
- 实现方式
- 编程式 实现
ImportSelector接口,并且将实现类声明称bean。 - 配置文件 META-INF/spring.factories
- 编程式 实现
Spring循环依赖
当bean的作用域是Prototype的是不支持循环依赖的。不然会出现套娃,
- 可能出现的依赖场景
- 构造器循环依赖
- 属性注入循环依赖
- Spring维护了三个Map,所谓的三级缓存。
- singletonObjects:第一级缓存,里面放置的是实例化好的单例对象
- earlySingletonObjects:第二级缓存,里面存放的是提前曝光的单例对象。
- singletonFactories:第三级缓存,里面存放的是要被实例化的对象的对象工厂。
- 创建bean的时候Spring首先从一级缓存singletonObjects中获取。如果获取不到,并且对象正在创建中,就再从二级缓存earlySingletonObjects中获取,如果还是获取不到就从三级缓存singletonFactories中取(Bean调用构造函数进行实例化后,即使属性还未填充,就可以通过三级缓存向外提前暴露依赖的引用值(提前曝光),根据对象引用能定位到堆中的对象,其原理是基于Java的引用传递),取到后从三级缓存移动到了二级缓存完全初始化之后将自己放入到一级缓存中供其他使用,因为加入singletonFactories三级缓存的前提是执行了构造器,所以构造器的循环依赖没法解决。
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/*
* 一级缓存
* singletonObjects 这就是人们常说的单例池,从微观意义上来说,这就是我们的 Spring 容器,
* 它用于存放完全初始化好的 bean,从缓存中取出的 bean 可以直接使用。
*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/*
* 三级缓存
* 存放 bean 工厂对象,提前曝光引用,解决循环依赖,虽然这个对象不完整,但是已经可以根据引用定位到堆内存中的对象,
* 此对象可能是通过构造方法创建,还没装配属性。
*/
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/*
* 二级缓存
* 存放原始的 bean 对象用于解决循环依赖,存到里面的对象还没有被填充属性。
*/
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Names of beans that are currently in creation */
// 标记为正在创建的 bean 的集合(A 依赖于 B,实例化 A 的过程中发现依赖 B,就去创建 B,那么 A 就会放在此集合中)
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
}
首先尝试去从一级缓存 singletonObjects 单例池中去获取,没有获取到并且要获取的 Bean 正在创建中,再去查找二级缓存 earlySingletonObjects,如果还是没有找到,就再去三级缓存 singletonFactories 中去找,找到了就从三级缓存 singletonFactories 中移除,放入到二级缓存 earlySingletonObjects 中去,这样做的好处就是,如果还有其他对象尝试获取这个 Bean,那么可以直接从二级缓存中取出来,就不需要再调用 getEarlyBeanReference() 方法了。最终,创建好的 Bean,全部 put 到了单例池 singletonObjects 中了。
如何解决循环依赖
- 构造器循环依赖解决办法:在构造函数中使用@Lazy注解延迟加载。在注入依赖时,先注入代理对象,当首次使用时再创建对象说明:一种互斥的关系而非层次递进的关系,故称为三个Map而非三级缓存的缘由 完成注入;
Spring中Filter和Interceptor的区别
- Filter是基于函数回调(doFilter()方法)的,而Interceptor则是基于Java反射的(AOP思想)。
- Filter依赖于Servlet容器,而Interceptor不依赖于Servlet容器。
- Filter对几乎所有的请求起作用,而Interceptor只能对action请求起作用。
- Interceptor可以访问Action的上下文,值栈里的对象,而Filter不能。
- 在action的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。
- Filter在过滤是只能对request和response进行操作,而interceptor可以对request、response、handler、modelAndView、exception进行操作。
- interceptor 的执行顺序大致为:
- 请求到达 DispatcherServlet
- DispatcherServlet 发送至 Interceptor ,执行 preHandle
- 请求达到 Controller
- 请求结束后,postHandle 执行
- Spring 中主要通过 HandlerInterceptor 接口来实现请求的拦截,实现 HandlerInterceptor 接口需要实现下面三个方法:
- preHandle() – 在handler执行之前,返回 boolean 值,true 表示继续执行,false 为停止执行并返回。
- postHandle() – 在handler执行之后, 可以在返回之前对返回的结果进行修改
- afterCompletion() – 在请求完全结束后调用,可以用来统计请求耗时等等
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter{
private static final Logger logger = Logger.getLogger(ExecuteTimeInterceptor.class);
//before the actual handler will be executed
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
}
//after the handler is executed
public void postHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView)
throws Exception {
long startTime = (Long)request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
long executeTime = endTime - startTime;
//modified the exisitng modelAndView
modelAndView.addObject("executeTime",executeTime);
//log it
if(logger.isDebugEnabled()){
logger.debug("[" + handler + "] executeTime : " + executeTime + "ms");
}
}
}
- Servlet 的 Filter 接口需要实现如下方法:
void init(FilterConfig paramFilterConfig)– 当容器初始化 Filter 时调用,该方法在 Filter 的生命周期只会被调用一次,一般在该方法中初始化一些资源,FilterConfig 是容器提供给 Filter 的初始化参数,在该方法中可以抛出 ServletException 。init 方法必须执行成功,否则 Filter 可能不起作用,出现以下两种情况时,web 容器中 Filter 可能无效: 1)抛出 ServletException 2)超过 web 容器定义的执行时间。doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain)– Web 容器每一次请求都会调用该方法。该方法将容器的请求和响应作为参数传递进来, FilterChain 用来调用下一个 Filter。void destroy()– 当容器销毁 Filter 实例时调用该方法,可以在方法中销毁资源,该方法在 Filter 的生命周期只会被调用一次。
小结
AOP 以代理织入横切逻辑,注册方式决定 Bean 来源;自动装配通过 @EnableAutoConfiguration 与 SPI 加载配置,循环依赖靠三级缓存解决,构造器注入无法参与。