Issue
My 'applicationContext.xml' file for spring is:
<bean id="gzipResponseInterceptor" class="my.interceptor.GzipResponseInterceptor"/>
<bean id="addResponseInterceptor" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref local="httpClient"/>
</property>
<property name="targetMethod">
<value>addResponseInterceptor</value>
</property>
<property name="arguments">
<list>
<ref bean="gzipResponseInterceptor"/>
</list>
</property>
</bean>
<bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient">
<constructor-arg>
<bean class="org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager" p:defaultMaxPerRoute="100"
p:maxTotal="100"/>
</constructor-arg>
</bean>
Then in my Java code:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(context.getBean("gzipResponseInterceptor"));
System.out.println(context.getBean("addResponseInterceptor"));
System.out.println(context.getBean("httpClient"));
And it prints:
my.interceptor.GzipResponseInterceptor@525f1e4e
null
org.apache.http.impl.client.DefaultHttpClient@75f9eccc
Notice the value of the bean 'addResponseInterceptor' is null
! I can't understand why I can get null
for a spring bean.
Solution
The addResponseInterceptor
is a MethodInvokingFactoryBean
which sole purpose is, as the name implies, to invoke a method. When doing context.getBean("addResponseInterceptor")
what is being returned is the result of the getObject
method of the FactoryBean
.
The MethodInvokingFactoryBean
returns the result of the invoked method.
Judging by the name of the method being invoked, addResponseInterceptor
, that is void
. void
or Void
results in a null
result to be return from the MethodInvokingFactoryBean
.
If you want the actual FactoryBean
add a &
to the name of the bean you want to retrieve. See last part of section 5.8.3 of the reference guide.
Answered By - M. Deinum
Answer Checked By - Gilberto Lyons (JavaFixing Admin)