spring对类的实例化,定义了接口InstantiationStrategy,同时先做了个简单实现类SimpleInstantiationStrategy。采用实现部分,抽象部分的策略。为了更好的扩展性,把一部分再次抽象,后面可以采用多种实现方式。
 
     下面具体代码分析:
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    // FactoryMethod的ThreadLocal对象,线程所有的变量
private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<Method>(); // 返回当前线程所有的FactoryMethod变量值
public static Method getCurrentlyInvokedFactoryMethod() {
return currentlyInvokedFactoryMethod.get();
} // 第一种实例化方法,实现部分,部分抽象
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
// bd对象定义里,是否包含MethodOverride列表;spring有两个标签参数会产生MethodOverrides ,分别是 lookup-method,replaced-method
// 没有MethodOverride对象,可以直接实例化
if (bd.getMethodOverrides().isEmpty()) {
// 实例化对象的构造方法
Constructor<?> constructorToUse;
// 锁定对象,使获得实例化构造方法线程安全
synchronized (bd.constructorArgumentLock) {
// 查看bd对象里是否含有
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
// 没有就生成
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
// 生成成功后,赋值给bd对象,后面使用
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Exception ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 反射生成对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// 有MethodOverride对象,需要使用另一种实现方式,之类实现
return instantiateWithMethodInjection(bd, beanName, owner);
}
} // 第一种实例化方法的抽象部分
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
} // 第二种实例化方法,实现部分,抽象部分
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
final Constructor<?> ctor, Object... args) {
// 查看bd对象是否有MethodOverride对象
// 没有MethodOverride,则直接实例化对象
if (bd.getMethodOverrides().isEmpty()) {
if (System.getSecurityManager() != null) {
// use own privileged to change accessibility (when security is on)
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
ReflectionUtils.makeAccessible(ctor);
return null;
}
});
}
// 反射实例化对象
return BeanUtils.instantiateClass(ctor, args);
}
else {
// 有MethodOverride,之类实现实例化方法
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
} // 第二种实例化方法的抽象部分
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
} // 第三种实例化方法,全部实现
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
Object factoryBean, final Method factoryMethod, Object... args) { try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
ReflectionUtils.makeAccessible(factoryMethod);
return null;
}
});
}
else {
ReflectionUtils.makeAccessible(factoryMethod);
} // currentlyInvokedFactoryMethod,这块暂时还没看到在哪个地方用到了
// 先取出原有的 Method
Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
try {
// 设置当前的Method
currentlyInvokedFactoryMethod.set(factoryMethod);
// 使用factoryMethod实例化对象
return factoryMethod.invoke(factoryBean, args);
}
finally {
// 实例化完成,恢复现场
if (priorInvokedFactoryMethod != null) {
currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
}
else {
currentlyInvokedFactoryMethod.remove();
}
}
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(factoryMethod.getReturnType(),
"Illegal arguments to factory method '" + factoryMethod.getName() + "'; " +
"args: " + StringUtils.arrayToCommaDelimitedString(args), ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(factoryMethod.getReturnType(),
"Cannot access factory method '" + factoryMethod.getName() + "'; is it public?", ex);
}
catch (InvocationTargetException ex) {
String msg = "Factory method '" + factoryMethod.getName() + "' threw exception";
if (bd.getFactoryBeanName() != null && owner instanceof ConfigurableBeanFactory &&
((ConfigurableBeanFactory) owner).isCurrentlyInCreation(bd.getFactoryBeanName())) {
msg = "Circular reference involving containing bean '" + bd.getFactoryBeanName() + "' - consider " +
"declaring the factory method as static for independence from its containing instance. " + msg;
}
throw new BeanInstantiationException(factoryMethod.getReturnType(), msg, ex.getTargetException());
}
} }
 
注:lookup-method, replaced-method的使用,可以看之前的文章。 
 

spring实例化二:SimpleInstantiationStrategy的更多相关文章

  1. Spring实例

    Spring实例 上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们 ...

  2. spring实例教程

    1.配置好spring mvc发现访问无法匹配,很可能是文件放的位置或者相对目录不对. 2.实例大全:http://www.yiibai.com/spring/spring-collections-l ...

  3. 深入浅出Spring(四) Spring实例分析

    上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...

  4. [置顶] 深入浅出Spring(四) Spring实例分析

    上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...

  5. Redis + Jedis + Spring 实例(对象的操作)

        目录(?)[+] 不得不说,用哈希操作来存对象,有点自讨苦吃! 不过,既然吃了苦,也做个记录,也许以后API升级后,能好用些呢?! 或许,是我的理解不对,没有真正的理解哈希表. 一.预期 接上 ...

  6. spring实例入门

    首先是bean文件: package onlyfun.caterpillar; public class HelloBean {    private String helloWord = " ...

  7. spring 实例 bean 的方式

    一.使用构造器实例化: <bean id="personService" class="cn.mytest.service.impl.PersonServiceBe ...

  8. dubbo+zookeeper+spring实例

    互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,Dubbo是一个分布式服务框架,在这种情况下诞生的.现在核心业务抽取出来,作为独立的服务,使 ...

  9. Struts2 + Spring + hibernate 框架搭成实例

    1.准备Jar包: struts2.hibernate.spring所需jar包   struts-core-2.x.x.jar  ----struts核心包 xwork-core-2.x.x.jar ...

随机推荐

  1. 【单元测试框架unittest】

  2. selenium + python 环境配置 (一)

    超级无敌菜鸟 终于有空学习一下python 和 selenium 啦 第一步: 环境配置  (Windows版) 1. 下载安装python 根据你的电脑,下载一个python吧   这儿装的是pyt ...

  3. Linux安装 PostgreSQL

    1.在线安装 yum install postgresql-server -y 2.初始化数据库 service postgresql initdb 3.设置自动启动 hkconfig postgre ...

  4. Word 查找替换高级玩法系列之 -- 查找文档中的叠字

    叠字,顾名思义,就是重复出现,叠加在一起的文字,多多少少.点点滴滴等都属于这类范畴.而当Word文档中出现这类文字的时候我们应该怎么鉴别呢?如何找到这些叠字? 李清照的<声声慢>一词相信大 ...

  5. 小程序文案过长,‘收起/展开’文字,createSelectorQuery 获取节点成功,boundingClientRect 返回信息null

    问题描述: wxml中id是动态生成的. 获取节点信息是在onReady生命周期函数内延时500ms执行的,select(id)可以获取全部节点信息,boundingClientRect (rect) ...

  6. hdu 1002 prime 模板

    Constructing Roads Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  7. Spring Boot 使用 @Scheduled 注解创建定时任务

    在项目开发中我们经常需要一些定时任务来处理一些特殊的任务,比如定时检查订单的状态.定时同步数据等等. 在 Spring Boot 中使用 @Scheduled 注解创建定时任务非常简单,只需要两步操作 ...

  8. C#基础--go to

    goto语句的用法非常灵活,你可以用它实现很多功能,但是由于goto语句的跳转影响程序的结构,在使用的时候会使人迷茫,所以一般"教材"上都不建议使用,但是用它可以实现递归,循环,选 ...

  9. vue.js入门语法

    1.入门 <div id="vue_det"> <h1>site : {{site}}</h1> //两个大括号显示参数 <h1>u ...

  10. dotnetcore下解压zip文件,解决中文文件名乱码问题

    (迄今为止网上那些说的用Encoding.Default解决中文文件名乱码的都不能真正解决问题!) 1.在程序开始处 Encoding.RegisterProvider(CodePagesEncodi ...