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. python选课系统demo的小练习

    #简化选课系统代码:先登陆,然后判断身份并实例化,根据身份对应的类,让用户选择 class Manager: operate_dict=[ ('创造学生账号',"creat_student& ...

  2. DDS工作原理及其性能分析

    DDS工作原理及其性能分析 声明:引用请注明出处http://blog.csdn.net/lg1259156776/ 系列博客说明:此系列博客属于作者在大三大四阶段所储备的关于电子电路设计等硬件方面的 ...

  3. php utf8 gbk 数组 互转

    这些都是工作中常用的 前几年写过 但没有记录的习惯,后边有要用到麻烦,现在记录下 以后直接拿来用 数组里的 utf8_to_gbk 方法 是上一篇写的 直接调用 public static funct ...

  4. with as用法 --Python

    有些任务,可能事先设置,时候做清理工作,如下面一段程序: f = open('tmp.txt') data = f.read() print(data) 是不是忘了什么?没错,很明显忘记关闭文件句柄. ...

  5. 彻底理解JavaScript中的prototype、__proto__

    虽然在JavaScript里一切皆对象,但为了理解原型链系统,我们需要将JavaScript的对象分为对象和函数两大类.在此基础上,JavaScript的原型链逻辑遵从以下通用规则: 对象有__pro ...

  6. gdb 常用命令总结(精优)

    格式说明: [xxx]:可选参数,即可以指定可以不指定,实际输入的内容是 xxx <xxx>:占位参数,即必须指定的参数,实际输入的内容是 xxx gdb 常用命令: gdb [file] ...

  7. Python print函数详解

    1 """ 2 print(...) 3 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=Fals ...

  8. SVN迁移到Gitlab实践经历

    svn 迁移至git操作手册 项目交付.版本管理工具变更等情况下,迁移svn旧历史记录有很大必要,方便后续追踪文件的提交历史,文件修改记录比对等.git自带了从svn迁移至git的工具命令,可很好的对 ...

  9. 数据校验-hibernate-validator

    数据校验 在web开发时,对于请求参数,一般上都需要进行参数合法性校验的,原先的写法时一个个字段一个个去判断,这种方式太不通用了,所以java的JSR 303: Bean Validation规范就是 ...

  10. docker相关--dockerd日志设置

    背景 线上容器dockerd的后台程序打印了超过几十G的日志 Docker daemon日志的位置: Docker daemon日志的位置,根据系统不同各不相同. Ubuntu - /var/log/ ...