Research Log of Web Science Students

Computer Science is not simply programming

MethodInvokingBean: Wiring with two arguments in Spring

leave a comment »

Another case of duplicating code in my app:

Twitter twitter = new Twitter();
twitter.setOAuthConsumer("consumerKey","consumerSecret");

The first solution I thought of was eliminate the duplicate code using dependency injection. Only that I thought you can only wire properties
one by one like for example:

<bean  id="MyPageController"
class="com.hardwire.controller.MyPageController">
 <property name="twitterService" ref="twitterService"/>
 <property name="userService" ref="googleUserService"/>
</bean>

But with Spring’s MethodInvokingBean, this can be instantiated and injected to the objects who need it.

<bean id="twitter" class="twitter4j.Twitter"></bean>

<bean id="twitterInjector" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="twitter"/>
<property name="targetMethod">
              <value>setOAuthConsumer</value>
</property>
<property name="arguments">
     <list>
       	<value>consumerKey</value>
       	<value>consumerSecret</value>
     </list>
 </property>
 </bean>    

Advertisements

Written by Jose Asuncion

September 3, 2009 at 6:06 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: