《spring揭秘》读书笔记三

 bean的scope

  1. singleton, scope默认值为singleton

 spring容器中 scope='singleton'与单例模式不是一个意思。标记为singleton的bean是由容器来保证这种类型的bean在同一个容器中只存在一个共享实例;而Singleton模式则是保证在同一个Classloader中只存在一个这种类型的实例。

  可以从两个方面来看待singleton的bean所具有的特性。

     1). 对象实例数量。 singleton类型的bean定义,在一个容器中只存在一个共享实例,所有对该类型bean的依赖都引用这一单一实例。
    2). 对象存活时间。 singleton类型bean定义, 从容器启动,到它第一次被请求而实例化开始,只要容器不销毁或者退出,该类型bean的单一实例就会一直存活。

2. prototype

   针对声明为拥有prototype scope的bean定义,容器在接到该类型对象的请求的时候,会每次都重新生成一个新的对象实例给请求方。 容器每次返回给请求方一个新的对象实例之后,容器就不再拥有当前返回对象的引用,就任由这个对象实例“自生自灭”了。

  对于那些请求方不能共享使用的对象类型,应该将其bean定义的scope设置为prototype。这样,每个请求方可以得到自己对应的一个对象实例。通常,声明prototype的scope的bean定义类型,都是一些有状态的,比如保存每个顾客信息的对象

   
3. factorybean

   FactoryBean是Spring容器提供的一种可以扩展容器对象实例化逻辑的接口,请不要将其与容器名称BeanFactory相混淆。FactoryBean,其主语是Bean,定语为Factory,也就是说,它本身与其他注册到容器的对象一样,只是一个Bean而已,只不过,这种类型的Bean本身就是生产对象的工厂(Factory)。


4. 方法注入

   被注入的方法必须满足如下定义:

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

<bean id="newsBean" class="..domain.FXNewsBean" scope="prototype">
</bean>

<bean id="mockPersister" class="..impl.MockNewsPersister">
  <lookup-method name="getNewsBean" bean="newsBean"/>
</bean>

  通过<lookup-method>的name属性指定需要注入的方法名,  bean属性指定需要注入的对象,当getNewsBean方法被调用的时候,容器可以每次返回一个新的FXNewsBean类型的实例。

  5. 方法替换

     与方法注入只是通过相应方法为主体对象注入依赖对象不同,方法替换更多体现在方法的实现层面上,它可以灵活替换或者说以新的方法实现覆盖掉原来某个方法的实现逻辑。基本上可以认为,方法替换可以帮助我们实现简单的方法拦截功能。基本做到AOP(面向切面编程)的功能了。

    方法替换需要我们提供的类实现org.springframework.beans.factory.support.MethodReplacer接口

public class FXNewsProviderMethodReplacer implements MethodReplacer {

	private static final transient Log logger = LogFactory.getLog(FXNewsProviderMethodReplacer.class);

	public Object reimplement(Object target, Method method, Object[] args) throws Throwable {
		logger.info("before executing method["+method.getName()+"] on Object["+target.getClass().getName()+"].");
		System.out.println("sorry,We will do nothing this time.");
		logger.info("end of executing method["+method.getName()+"] on Object["+target.getClass().getName()+"].");
		return null;
	} 
}
<bean id="djNewsProvider" class="..FXNewsProvider">
    <constructor-arg index="0">
        <ref bean="djNewsListener"/>
    </constructor-arg>
    <constructor-arg index="1">
        <ref bean="djNewsPersister"/>
    </constructor-arg>

    <!-- 方法替换 -->
    <replaced-method name="getAndPersistNews" replacer="providerReplacer">
    </replaced-method>
</bean>

<bean id="providerReplacer" class="..FXNewsProviderMethodReplacer">
</bean>

<!--其他bean配置-->
...
发布了605 篇原创文章 · 获赞 47 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/104805045