tags:

views:

79

answers:

3

I have two spring bean Service classes in my project. Is it possible to call on from another? if yes, how it can be done?

+4  A: 

I have two spring bean Service classes in my project. Is it possible to call on from another? if yes, how it can be done?

The canonical approach would be to declare a dependency on the second service in the first one and to just call it.

public class FooImpl implements Foo {
    private Bar bar; // implementation will be injected by Spring

    public FooImpl() { }
    public FooImpl(Bar bar) { this.bar = bar; }

    public void setBar(Bar bar) { this.bar = bar; }
    public Bar getBar() { return this.bar; }

    public void doFoo() {
        getBar().doBar();
    }
}

And configure Spring to wire things together (the core job of Spring) i.e. inject a Bar implementation into your Foo service.

Pascal Thivent
I'm not sure what you mean by it. I've less experience in this framework. If you could explain it, it will help me to solve it.
Joe
can you explain it. I've two different service classes.
Joe
@Joe I don't know how to explain things more clearly. What are you asking for exactly? A tutorial about Spring?
Pascal Thivent
I got it. Sorry for my last comment asking for explanation as it was already explaining a lot. :D
Joe
@Joe No problem. It's just that, at some point, you have to read the documentation a bit (you need some understanding of the dependency injection part of Spring to use it) and to write some code yourself. The good news is that Spring documentation is really good. Good luck.
Pascal Thivent
A: 

This is the point of using a dependency injection framework. The idea is that you simply declare dependencies, the framework connects them. e.g.

Class A{ 
  private B b;
  public void setB(B b) { this. b=b;}
}

Class B{
  ....
}

You then wire up the framework to inject the B instance into the A. If you get an A from the framework, the B is already provided. There should be no code where you explicitly set the B instance in the A instance.

Look up some references to dependency injection

Steve B.
A: 

You can call anything from anything else in spring, so long as you have access to the context or bean factory where the services exist. If you don't want to traverse the contexts, you could simply pass the service references to either service in your configuration file.

Mondain