Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Spring service class from another

Tags:

java

spring

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?

like image 377
Joe Avatar asked Sep 06 '10 02:09

Joe


1 Answers

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.

like image 100
Pascal Thivent Avatar answered Sep 30 '22 02:09

Pascal Thivent