Sastrija
Sastrija

Reputation: 3384

Calling a Spring service class from another

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

Upvotes: 5

Views: 14454

Answers (3)

Paul Gregoire
Paul Gregoire

Reputation: 9793

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.

Upvotes: 0

Pascal Thivent
Pascal Thivent

Reputation: 570635

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.

Upvotes: 6

Steve B.
Steve B.

Reputation: 57333

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

Upvotes: 0

Related Questions