The observer pattern and springframework

Today I present you how you can use the famous Observer design pattern with the (not THAT) famous spring framework.

Wiring of objects with other objects should be easy done. They objects shouldn’t be tightly coupled. But where do you wire the objects?
At the start of you application? In factories?

If you are already using the springframework, you can wire beans with each other using the MethodInvokingFactoryBean. Essentially this class can be used
to invoke method calls with your bean definition.

Imagine you have a bean named subjectBean which implements java’s or your custom Subject interface. The class of the subjectBean now offers a public method
addObserver. Now you can register an Observer with the subjectBean.
This sound complicated, but here is the simple example:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"><ref local="subjectBean"/></property>
<property name="targetMethod"><value>addObserver</value></property>
<property name="arguments">
<ref bean="anObserver"/>

You can see that there is no id necessary. Because we don’t need or want to reference to this spring bean.
This tips is from the Enterprise Java Community and helped me a lot. Thx


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: