views:

47

answers:

3

I need to call public methods of the rubberStampService from inside the RubberStampServiceImpl class.

To reference the rubberStampService from inside itself, can I make a self-referential bean declaration like this:

<beans:bean id="rubberStampService" class="com.rubberly.RubberStampServiceImpl">
    <beans:property name="rubberStampService" ref="rubberStampService" />
</beans:bean>
+1  A: 

Your service should be able to call public methods on itself without resorting to this.

Nathan Hughes
I think the poster should be resorting to this!- the keyword ;-)
Pablojim
+2  A: 

Sounds like an infinitely recursive, out of memory error waiting to happen. Why not just have the service call its own method and be done with it? You don't need a new reference, just "this".

public interface FooService()
{
    void foo();
    void bar();
}

public class FooServiceImpl implements FooService
{
    public void foo() { System.out.println("calling foo"); }
    public void bar()
    {
        this.foo(); // just call your own method.
    }
}
duffymo
+1  A: 

Can't see any problems with this approach.

Spring can handle circular dependencies (if they are resolveable, i.e. if you don't use constructor injection), including the case of self-referencing bean. The only difference is that in the case of circular dependecies beans may be not fully initialized when they are injected.

It may be useful when bean can be configured to use different collaborators, but in some specific case it need to use itself.

See also:

axtavt