Spring闲谈

依赖注入(Inverse of Control)


Spring 实现IoC(Inverse of Control),就是通过 Spring容器 来创建,管理所有的Java对象(Java Bean)。
并且Spring容器使用配置文件来组织各个Java Bean之间的依赖关系,而不是以硬编码的方式让它们耦合在一起!
没有各种new真爽,配置文件管理各个Bean 之间的协作关系真的炒鸡解耦,谁用谁知道。

Bean 的作用域 singleton (默认) ,prototyperequestsessionglobal session 后面三个只在web应用中有效

创建Bean的三种形式

  • 构造器,最常见的形式,如果不采用构造注入,Spring底层会调用Bean类的无参数构造器来创建实例,因此要求该Bean类提供无参数的构造器。Spring容器会默认初始化所有属性,基础类型0或false,引用类型null

  • 静态工厂 ,要创建的实例的Bean,class属性要是静态工厂类(因为Spring需要的是哪个工厂类来创建Bean实例),用factory-method指定工厂方法

    ```
      package com.example.factory;
    
      public class ExampleFactory{  //静态工厂方法
      public static Example newInstance(String message,int index){  
          return  new Example(message,index);  
      }  
    
      ---- xml配置文件
      <beans>
        <bean id = "byIndex"  class = "com.example.ExampleFactory"
             factory-method="newInstance">
            <constructor-arg index="0" value="Hello World!"/>  
            <constructor-arg index="1" value="1"/>  
        </bean>
     </beans>
     ```
    
  • 实例工厂,先配置实例工厂类,配置Bean无需class属性, 用factory-bean指定工厂类id,factory-method指定工厂方法

      ---- xml配置文件
      <beans>
          <bean id = "exampleFactory" class = "com.example.ExampleFactory"/>
    
          <bean id = "byName"  factory-bean = "exampleFactory" 
              factory-method="newInstance">
            <constructor-arg name="message" value="Hello World!"/>  
            <constructor-arg name="index" value="1"/>  
          </bean>
     </beans>
    

循环依赖问题


  • 构造器注入的循环依赖问题是无法解决的
  • setter循环依赖是可以提前暴露刚完成的构造器来解决(需要是singleton)

怎么检测循环依赖

检测循环依赖相对比较容易,Bean在创建的时候可以给该Bean打标,如果递归调用回来发现正在创建中的话, 即说明了循环依赖了。

Spring容器将每一个正在创建的Bean 标识符放在一个“当前创建Bean池”中,Bean标识符在创建过程中将一直保持在这个池中,因此如果在发现已经在“当前创建Bean池”里,将抛出BeanCurrentlyInCreationException异常表示循环依赖;而对于创建完毕的Bean将从“当前创建Bean池”中清除掉。

//DefaultSingletonBeanRegistry
protected void beforeSingletonCreation(String beanName) {        
  if (!this.singletonsCurrentlyInCreation.add(beanName)) {            
    throw new BeanCurrentlyInCreationException(beanName);       
  }    
}

怎么检测循环依赖

提前暴露。
假如A,B循环依赖

  1. 实例A,将未注入属性的A,暴露给容器(Wrap)
  2. 给A注入属性,发现要用B
  3. 实例B,注入属性,发现要用A,在单例缓存中没有找到A,又去Warp中找到了,注入完成
  4. 递归回来,A成功注入B
//初始化Bean之前提前把Factory暴露出去
addSingletonFactory(beanName, new ObjectFactory() {                
  public Object getObject() throws BeansException {                   
   return getEarlyBeanReference(beanName, mbd, bean);                
  }            
});

//通过暴露Factory的方式暴露,是因为有些Bean是需要被代理的
protected Object getEarlyBeanReference(String beanName, 
RootBeanDefinition mbd, 
Object bean) {        
  Object exposedObject = bean;        

  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {            
    for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) {               
       BeanPostProcessor bp = (BeanPostProcessor) it.next();             

       if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {                   
        SmartInstantiationAwareBeanPostProcessor ibp 
          = (SmartInstantiationAwareBeanPostProcessor) bp;                    
        exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);               
       }          
    }        
  }        
  return exposedObject;   
}

// 在Bean 的单例缓存中获取Bean
protected Object getSingleton(String beanName, boolean allowEarlyReference) {        
  Object singletonObject = this.singletonObjects.get(beanName);        
  if (singletonObject == null) {           
   synchronized (this.singletonObjects) {               
      // 单例缓存中没有,找提前暴露的                
      singletonObject = this.earlySingletonObjects.get(beanName);
      if (singletonObject == null && allowEarlyReference) {                    
        ObjectFactory singletonFactory = (ObjectFactory) this
                            .singletonFactories.get(beanName);       
             
        // 如果只是提前暴露了工厂(没有实例),执行工厂方法         
          if (singletonFactory != null) {                                           
            singletonObject = singletonFactory.getObject(); 
            this.earlySingletonObjects.put(beanName, singletonObject);                      
            this.singletonFactories.remove(beanName);                   
         }               
       }            
    }       
   }       
 return (singletonObject != NULL_OBJECT ? singletonObject : null);    
}

Spring 的几个缓存池 :

  • alreadyCreated:已经创建好的Bean ,检测创建好的Bean是否依赖正在创建的Bean,如果是,说明原创建好多不可用了
  • singletonObjects:单例Bean
  • singletonFactories : 单例Bean 提前暴露的工厂
  • earlySingletonObjects:执行了工厂方法生产出的Bean
  • singletonsCurrentlyCreation:创建中的Bean ,用于检测循环依赖

所以循环依赖无法解决的有
构造器注入
代理类改变了Bean的版本(见alreadyCreated,提前暴露的别的Bean 依赖了,之后)
原型Bean (prototype)
参考乌哇哇这里


协调不同步的Bean


简单的说,一个如果一个singleton的Bean 依赖一个prototype 的Bean的时候,会产生不同步的情况(因为singleton只创建一次,当singleton调用 prototype 的时候,一般的注入没办法让 Spring 容器每次都返回一个新的 prototype的Bean)。
两种方法:

  1. 让singleton 的bean 实现 ApplicationContextAware 接口
public class A implements ApplicationContextAware {  
    //用于保存ApplicationContext的引用,set方式注入  
    private ApplicationContext applicationContext;  
    //模拟业务处理的方法  
    public Object process(){  
        B b = createB();  
        return b.execute();  
    }  
    private B createB() {  
        return (B) this.applicationContext.getBean("b"); //  
    }    
    public void setApplicationContext(ApplicationContext applicationContext)  
            throws BeansException {  
        this.applicationContext=applicationContext;//获得该ApplicationContext引用  
    }  
}  

2 . lookup 方法

public abstract class A{  
    //模拟业务处理的方法  
    public Object process(){  
        B b= createB();  
        return b.execute();  
    }  
    protected abstract B createB();  
}  

<bean id="b" class="com.example.B" scope="prototype"/>  
<bean id="a" class="com.example.A">  
      <lookup-method name="createB" bean="b"/>  
</bean>  

推荐用第二种方法,这样和Spring的代码没有耦合。
createB() 方法是个抽象方法,我们并没有实现它啊,那它是怎么拿到B类的呢。这里的奥妙就是Srping应用了CGLIB(动态代理)类库。这个方法是不是抽象都无所谓,不影响CGLIB动态代理。
在这个方法的代码签名处有个标准:

<public|protected> [abstract] <return-type> theMethodName(no-arguments);

  • public|protected要求方法必须是可以被子类重写和调用的;
  • abstract可选,如果是抽象方法,CGLIB的动态代理类就会实现这个方法,如果不是抽象方法,就会覆盖这个方法,所以没什么影响;
  • return-type就是non-singleton-bean的类型咯,当然可以是它的父类或者接口。
  • no-arguments不允许有参数。

AOP

AOP (Aspect-OrientedProgramming,面向方面编程),是对OOP(Object-Oriented Programing,面向对象编程)的补充。
传统的OOP模式编程,会在每个类调用一些共同的方法(log,安全检查,事务,性能统计,异常处理等)。
这些方法会造成代码的冗余,而且曾加的代码的耦合性(功能逻辑和业务逻辑没有分开)

实现AOP的两种方式:

  • XML风格,使用<aop:config>

首先定义一个要被切的类


public interface PersonService {
    public String getPersonName(Integer id);
    public void save(String name);
}


public class PersonServiceBean implements PersonService {
    @Override
    public String getPersonName(Integer id) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void save(String name) {
        // TODO Auto-generated method stub
        System.out.println("您输入的是" + name);
    }    
}

然后,我们来定义切点类和切点


public class MyInterceptor {
    
    public void anyMethod(){}

    public void doBefore(String name){
        System.out.println("前置通知" + name);
    }
    
    public void doAfterReturn(String result){
        System.out.println("后置通知" + result);
    }
    
    public Object doAfter(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("进入方法");
        Object result = pjp.proceed();
        System.out.println("最终通知");
        return result;
    }
    
    public void doAfterThrowing(Exception e){
        System.out.println("异常通知" + e);
    }
    
    public void doAround(){
        System.out.println("环绕通知");
    }
}


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    
    <aop:config>
        <aop:aspect id="asp" ref="myInterceptor">
             <!-- 切点-->
            <aop:pointcut  id="mycut" 
      expression="execution(* cn.qdlg.service.impl.PersonServiceBean.*(..))"/>
            <aop:before pointcut-ref="mycut" method="doBefore"/>
            <aop:after pointcut-ref="mycut" method="doAfter"/>
            <aop:after-returning pointcut-ref="mycut" method="doAfterReturn"/>
            <aop:around pointcut-ref="mycut" method="doAround"/>
            <aop:after-throwing pointcut-ref="mycut" method="doAfterThrowing"/>
        </aop:aspect>
    </aop:config>

    <bean id="myInterceptor" class="cn.qdlg.service.MyInterceptor"></bean>
    <bean id="PersonService" class="cn.qdlg.service.impl.PersonServiceBean"></bean>
</beans>
  • @Aspect 风格
//启动 aspectj 代理
<aop:aspectj-autoproxy proxy-target-class="true"/>

public class MyInterceptor {
    @Pointcut("execution (* cn.qdlg.service.impl.PersonServiceBean.*(..))")
    public void anyMethod(){}

    @Before("anyMethod()")
    public void doBefore(String name){
        System.out.println("前置通知" + name);
    }
    
    @AfterReturning("anyMethod() && args(name)")
    public void doAfterReturn(String result){
        System.out.println("后置通知" + result);
    }
    
    @After("anyMethod()")
    public Object doAfter(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("进入方法");
        Object result = pjp.proceed();
        System.out.println("最终通知");
        return result;
    }
    
    @AfterThrowing("anyMethod()")
    public void doAfterThrowing(Exception e){
        System.out.println("异常通知" + e);
    }
    
    @Around("anyMethod()")
    public void doAround(){
        System.out.println("环绕通知");
    }
}

AOP 实现的方式,动态代理----- >http://www.jianshu.com/p/6411406ef7c3

https://my.oschina.net/elain/blog/382494

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容