原创 Spring源代码分析(9)---FactoryBean(我是谁,谁是我,谁是谁) 收藏
本节,我们最分析ioc的最后一个核心点,那就是FactoryBean;
在ioc中,存在着这样的一种bean,他的引用并不是只想他自身,而是通过折射指向了别的bean,就因为他的存在,使得他支持了jdbc,jndi等多种j2ee技术,他维持了 spring的80%的功能的实现,那么,就让我们来详细的分析一些这个神奇的bean,就好像武林外传里面的秀才杀死姬无命一样的,谁到底是谁,我们看似在取得factoryBean,却拿到了另外的一个类,失之东隅,收之桑榆;
我们以 MethodInvokingFactoryBean为例子,这是一个很奇妙的bean,如下配置:
1. <bean name="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
2. <property name="staticMethod">
3. <value>org.corey.demo.Demo.staticMethod</value>
4. </property>
5. </bean>
6.
7.
8.
我们在代码:
1. ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
2.
3. ac.getBean("methodInvoke");
1. ac.getBean("methodInvoke");返回的是org.corey.demo.Demo 类的staticMethod方法的返回值;
那么,我们来看一下这些都是怎么实现的:
我们具体来看下几个类的代码:
1. public interface FactoryBean {
2.
3.
4. Object getObject() throws Exception;
5.
6. Class getObjectType();
7.
8.
9. boolean isSingleton();
10.
11. }
InitializingBean 接口的话,我们已经不用介绍了;
MethodInvoker类主要含有这几个类:
1. private Class targetClass;
2.
3. private Object targetObject;
4.
5. private String targetMethod;
6.
7. private Object[] arguments;
8.
9. // the method we will call
10. private Method methodObject;
MethodInvoker 类正式实现了MethodInvokingFactoryBean方法转嫁的核心功能,我们从入口来分析一下这个类:
1. public void afterPropertiesSet() throws Exception {
2. prepare();
3. if (this.singleton) {
4. Object obj = doInvoke();
5. this.singletonObject = (obj != null ? obj : MethodInvoker.VOID);
6. }
7. }
这是MethodInvokingFactoryBean的初始化方法:
1. ublic void prepare() throws ClassNotFoundException, NoSuchMethodException {
2. if (this.targetClass == null) {
3. throw new IllegalArgumentException("Either targetClass or targetObject is required");
4. }
5. if (this.targetMethod == null) {
6. throw new IllegalArgumentException("targetMethod is required");
7. }
8.
9. if (this.arguments == null) {
10. this.arguments = new Object[0];
11. }
12.
13. Class[] argTypes = new Class[this.arguments.length];
14. for (int i = 0; i < this.arguments.length; ++i) {
15. argTypes[i] = (this.arguments[i] != null ? this.arguments[i].getClass() : Object.class);
16. }
17.
18. // Try to get the exact method first.
19. try {
20. this.methodObject = this.targetClass.getMethod(this.targetMethod, argTypes);
21. }
22. catch (NoSuchMethodException ex) {
23. // Just rethrow exception if we can't get any match.
24. this.methodObject = findMatchingMethod();
25. if (this.methodObject == null) {
26. throw ex;
27. }
28. }
29.
30. if (this.targetObject == null && !Modifier.isStatic(this.methodObject.getModifiers())) {
31. throw new IllegalArgumentException("Target method must not be non-static without a target");
32. }
33. }
将你在xml文件中配置的MethodInvokingFactoryBean的属性(字符串)转化成为元数据,为等下的调用做准备;
1. private Object doInvoke() throws Exception {
2. try {
3. return invoke();
4. }
5. catch (InvocationTargetException ex) {
6. if (ex.getTargetException() instanceof Exception) {
7. throw (Exception) ex.getTargetException();
8. }
9. if (ex.getTargetException() instanceof Error) {
10. throw (Error) ex.getTargetException();
11. }
12. throw ex;
13. }
14. }
1. public Object invoke() throws InvocationTargetException, IllegalAccessException {
2. if (this.methodObject == null) {
3. throw new IllegalStateException("prepare() must be called prior to invoke() on MethodInvoker");
4. }
5. // In the static case, target will just be <code>null</code>.
6. return this.methodObject.invoke(this.targetObject, this.arguments);
7. }
8.
9.
在这里分别调用了开始准备的目标类和目标方法;得到结果并且把他存储在singletonObject中,
在factoryBean接口中,实现了这个方法:
1. public Object getObject() throws Exception {
2. if (this.singleton) {
3. // Singleton: return shared object.
4. return this.singletonObject;
5. }
6. else {
7. // Prototype: new object on each call.
8. Object retVal = doInvoke();
9. return (retVal != null ? retVal : MethodInvoker.VOID);
10. }
11. }
用 getObject把真正的bean返回出去了,那么,现在我们的疑问来了,我们在getBean的时候,什么时候调用了这个getObject()方法呢???
我们来看一下getBean的实现:
在AbstractBeanFactory中,
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException
是一个典型的模板模式的应用,他的createBean();在 AbstractAutowireCapableBeanFactory实现,他负责从BeanDefinition构造出一个Objct,而 getBean在拿到这个Object后,就会调用第三步:
bean = getObjectForSharedInstance(name, sharedInstance);
从这个Object类中拿到一个真正我们要返回出去的bean,而这里主要就是我们的factoryBean的处理;
1. protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {
2. String beanName = transformedBeanName(name);
3.
4. // Don't let calling code try to dereference the
5. // bean factory if the bean isn't a factory.
6. if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
7. throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
8. }
9.
10. // Now we have the bean instance, which may be a normal bean or a FactoryBean.
11. // If it's a FactoryBean, we use it to create a bean instance, unless the
12. // caller actually wants a reference to the factory.
13. if (beanInstance instanceof FactoryBean) {
14. if (!isFactoryDereference(name)) {
15. // Return bean instance from factory.
16. FactoryBean factory = (FactoryBean) beanInstance;
17. if (logger.isDebugEnabled()) {
18. logger.debug("Bean with name '" + beanName + "' is a factory bean");
19. }
20. try {
21. beanInstance = factory.getObject();
22. }
23. catch (Exception ex) {
24. throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
25. }
26. if (beanInstance == null) {
27. throw new FactoryBeanNotInitializedException(
28. beanName, "FactoryBean returned null object: " +
29. "probably not fully initialized (maybe due to circular bean reference)");
30. }
31. }
32. else {
33. // The user wants the factory itself.
34. if (logger.isDebugEnabled()) {
35. logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
36. }
37. }
38. }
39.
40. return beanInstance;
41. }
transformedBeanName去掉了beanName的&符号;
isFactoryDereference(name)判断一个类名是不是以&开头,如果这个类是FactoryBean并且beanName以&开头,那么则返回这个FactoryBean的本身,如果不是以&开始,则返回他所要转换的类;
beanInstance = factory.getObject();
就这样,我们在不知不觉的就完成这次南水北调的转换! *_*
最后,我们来总结一下Spring代码的此功能实现,在整个实现中,spring的代码都很有调理,很好的体现了面向接口编程,几乎每个具体的类(工具类除外)都是从接口开始着手,并且一层一层就想洋葱一样展现在我们的眼前,比如,首先,抽象出来一个顶层的factoryBean接口,提供了bean转换的统一接口,为我们组合型模板方式提供了可能,我们只要在beanFactory中调用他的getObject,而不必管这个类是从jndi还是从别的类的方法中得到的,从而把BeanFactory与具体的FactoryBean实现解耦开来,而且在MethodInvokingFacrotyBean中,我们把转换方法的实现用继承的方式委托给了MethodInvoker,功能复用的方式有两种,一种如这个一样的继承,坏处就是这是一种编译器的复用,无法实现策略模式一样的转换算法的功能,但是他好的就是我们不用显示的把委托代码重新写一次,而组合复用的好处是我们可以更换不同的MethodInvoker的实现,如果这里的targetClass和targetMethod有另外的处理方式,即MethodInvoker有另外的实现方式,我们可以考虑使用,如果没有的话,我们选择更方便的继承方式;
在代码中,大量的使用了工具类,这是单一职责原则的体现,为了避免意外的情况发生,或者说用户的盲目扩展,很多公开地方做了防御性的判断,并且在意外情况发生,输入参数非法的地方,抛出了明确的异常,这正式代码大全里所说的防御性编程的良好的体现,往往是这么一些微小的细节,更加的体现了大牛们代码的质量;设计的合理;这些都是值得我们深入去研究的地方;
因为我也初出茅庐,这些文章也只是我看spring源代码的一些小小的心得,在分享给有需要的朋友的同时,其实更多的是给自己招一个随处可得的笔记本,希望大家能够多多交流,在前面的getBean方法中也许分析得有些模糊,但是通过前几节对反射的重新复习,cglib的应用和asm的了解,和对ioc的代码一些全局的了解,现在我们再去看getBean代码,基本上不存在着什么疑问,至少我是这样的;所以,我想ioc的分析,应该就差不多到这里了,而spring的微核就是这个ioc容器,搞清楚这些对我们将来分析外围打下一个良好的基础;
http://blog.csdn.net/turkeyzhou/archive/2008/09/24/2974922.aspx
本节,我们最分析ioc的最后一个核心点,那就是FactoryBean;
在ioc中,存在着这样的一种bean,他的引用并不是只想他自身,而是通过折射指向了别的bean,就因为他的存在,使得他支持了jdbc,jndi等多种j2ee技术,他维持了 spring的80%的功能的实现,那么,就让我们来详细的分析一些这个神奇的bean,就好像武林外传里面的秀才杀死姬无命一样的,谁到底是谁,我们看似在取得factoryBean,却拿到了另外的一个类,失之东隅,收之桑榆;
我们以 MethodInvokingFactoryBean为例子,这是一个很奇妙的bean,如下配置:
1. <bean name="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
2. <property name="staticMethod">
3. <value>org.corey.demo.Demo.staticMethod</value>
4. </property>
5. </bean>
6.
7.
8.
我们在代码:
1. ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
2.
3. ac.getBean("methodInvoke");
1. ac.getBean("methodInvoke");返回的是org.corey.demo.Demo 类的staticMethod方法的返回值;
那么,我们来看一下这些都是怎么实现的:
我们具体来看下几个类的代码:
1. public interface FactoryBean {
2.
3.
4. Object getObject() throws Exception;
5.
6. Class getObjectType();
7.
8.
9. boolean isSingleton();
10.
11. }
InitializingBean 接口的话,我们已经不用介绍了;
MethodInvoker类主要含有这几个类:
1. private Class targetClass;
2.
3. private Object targetObject;
4.
5. private String targetMethod;
6.
7. private Object[] arguments;
8.
9. // the method we will call
10. private Method methodObject;
MethodInvoker 类正式实现了MethodInvokingFactoryBean方法转嫁的核心功能,我们从入口来分析一下这个类:
1. public void afterPropertiesSet() throws Exception {
2. prepare();
3. if (this.singleton) {
4. Object obj = doInvoke();
5. this.singletonObject = (obj != null ? obj : MethodInvoker.VOID);
6. }
7. }
这是MethodInvokingFactoryBean的初始化方法:
1. ublic void prepare() throws ClassNotFoundException, NoSuchMethodException {
2. if (this.targetClass == null) {
3. throw new IllegalArgumentException("Either targetClass or targetObject is required");
4. }
5. if (this.targetMethod == null) {
6. throw new IllegalArgumentException("targetMethod is required");
7. }
8.
9. if (this.arguments == null) {
10. this.arguments = new Object[0];
11. }
12.
13. Class[] argTypes = new Class[this.arguments.length];
14. for (int i = 0; i < this.arguments.length; ++i) {
15. argTypes[i] = (this.arguments[i] != null ? this.arguments[i].getClass() : Object.class);
16. }
17.
18. // Try to get the exact method first.
19. try {
20. this.methodObject = this.targetClass.getMethod(this.targetMethod, argTypes);
21. }
22. catch (NoSuchMethodException ex) {
23. // Just rethrow exception if we can't get any match.
24. this.methodObject = findMatchingMethod();
25. if (this.methodObject == null) {
26. throw ex;
27. }
28. }
29.
30. if (this.targetObject == null && !Modifier.isStatic(this.methodObject.getModifiers())) {
31. throw new IllegalArgumentException("Target method must not be non-static without a target");
32. }
33. }
将你在xml文件中配置的MethodInvokingFactoryBean的属性(字符串)转化成为元数据,为等下的调用做准备;
1. private Object doInvoke() throws Exception {
2. try {
3. return invoke();
4. }
5. catch (InvocationTargetException ex) {
6. if (ex.getTargetException() instanceof Exception) {
7. throw (Exception) ex.getTargetException();
8. }
9. if (ex.getTargetException() instanceof Error) {
10. throw (Error) ex.getTargetException();
11. }
12. throw ex;
13. }
14. }
1. public Object invoke() throws InvocationTargetException, IllegalAccessException {
2. if (this.methodObject == null) {
3. throw new IllegalStateException("prepare() must be called prior to invoke() on MethodInvoker");
4. }
5. // In the static case, target will just be <code>null</code>.
6. return this.methodObject.invoke(this.targetObject, this.arguments);
7. }
8.
9.
在这里分别调用了开始准备的目标类和目标方法;得到结果并且把他存储在singletonObject中,
在factoryBean接口中,实现了这个方法:
1. public Object getObject() throws Exception {
2. if (this.singleton) {
3. // Singleton: return shared object.
4. return this.singletonObject;
5. }
6. else {
7. // Prototype: new object on each call.
8. Object retVal = doInvoke();
9. return (retVal != null ? retVal : MethodInvoker.VOID);
10. }
11. }
用 getObject把真正的bean返回出去了,那么,现在我们的疑问来了,我们在getBean的时候,什么时候调用了这个getObject()方法呢???
我们来看一下getBean的实现:
在AbstractBeanFactory中,
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException
是一个典型的模板模式的应用,他的createBean();在 AbstractAutowireCapableBeanFactory实现,他负责从BeanDefinition构造出一个Objct,而 getBean在拿到这个Object后,就会调用第三步:
bean = getObjectForSharedInstance(name, sharedInstance);
从这个Object类中拿到一个真正我们要返回出去的bean,而这里主要就是我们的factoryBean的处理;
1. protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {
2. String beanName = transformedBeanName(name);
3.
4. // Don't let calling code try to dereference the
5. // bean factory if the bean isn't a factory.
6. if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
7. throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
8. }
9.
10. // Now we have the bean instance, which may be a normal bean or a FactoryBean.
11. // If it's a FactoryBean, we use it to create a bean instance, unless the
12. // caller actually wants a reference to the factory.
13. if (beanInstance instanceof FactoryBean) {
14. if (!isFactoryDereference(name)) {
15. // Return bean instance from factory.
16. FactoryBean factory = (FactoryBean) beanInstance;
17. if (logger.isDebugEnabled()) {
18. logger.debug("Bean with name '" + beanName + "' is a factory bean");
19. }
20. try {
21. beanInstance = factory.getObject();
22. }
23. catch (Exception ex) {
24. throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
25. }
26. if (beanInstance == null) {
27. throw new FactoryBeanNotInitializedException(
28. beanName, "FactoryBean returned null object: " +
29. "probably not fully initialized (maybe due to circular bean reference)");
30. }
31. }
32. else {
33. // The user wants the factory itself.
34. if (logger.isDebugEnabled()) {
35. logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
36. }
37. }
38. }
39.
40. return beanInstance;
41. }
transformedBeanName去掉了beanName的&符号;
isFactoryDereference(name)判断一个类名是不是以&开头,如果这个类是FactoryBean并且beanName以&开头,那么则返回这个FactoryBean的本身,如果不是以&开始,则返回他所要转换的类;
beanInstance = factory.getObject();
就这样,我们在不知不觉的就完成这次南水北调的转换! *_*
最后,我们来总结一下Spring代码的此功能实现,在整个实现中,spring的代码都很有调理,很好的体现了面向接口编程,几乎每个具体的类(工具类除外)都是从接口开始着手,并且一层一层就想洋葱一样展现在我们的眼前,比如,首先,抽象出来一个顶层的factoryBean接口,提供了bean转换的统一接口,为我们组合型模板方式提供了可能,我们只要在beanFactory中调用他的getObject,而不必管这个类是从jndi还是从别的类的方法中得到的,从而把BeanFactory与具体的FactoryBean实现解耦开来,而且在MethodInvokingFacrotyBean中,我们把转换方法的实现用继承的方式委托给了MethodInvoker,功能复用的方式有两种,一种如这个一样的继承,坏处就是这是一种编译器的复用,无法实现策略模式一样的转换算法的功能,但是他好的就是我们不用显示的把委托代码重新写一次,而组合复用的好处是我们可以更换不同的MethodInvoker的实现,如果这里的targetClass和targetMethod有另外的处理方式,即MethodInvoker有另外的实现方式,我们可以考虑使用,如果没有的话,我们选择更方便的继承方式;
在代码中,大量的使用了工具类,这是单一职责原则的体现,为了避免意外的情况发生,或者说用户的盲目扩展,很多公开地方做了防御性的判断,并且在意外情况发生,输入参数非法的地方,抛出了明确的异常,这正式代码大全里所说的防御性编程的良好的体现,往往是这么一些微小的细节,更加的体现了大牛们代码的质量;设计的合理;这些都是值得我们深入去研究的地方;
因为我也初出茅庐,这些文章也只是我看spring源代码的一些小小的心得,在分享给有需要的朋友的同时,其实更多的是给自己招一个随处可得的笔记本,希望大家能够多多交流,在前面的getBean方法中也许分析得有些模糊,但是通过前几节对反射的重新复习,cglib的应用和asm的了解,和对ioc的代码一些全局的了解,现在我们再去看getBean代码,基本上不存在着什么疑问,至少我是这样的;所以,我想ioc的分析,应该就差不多到这里了,而spring的微核就是这个ioc容器,搞清楚这些对我们将来分析外围打下一个良好的基础;
http://blog.csdn.net/turkeyzhou/archive/2008/09/24/2974922.aspx