JiKra
JiKra

Reputation: 1790

Spring @Autowire another implementation of the current service

I need to have an interface and then two implementations in different maven modules. Both impl services see api modul with interface but they don't see each other.

There is a default implementation and then transactional implementation. I want transactional impl service just load and call default impl service. Like this:

package my.app.core.api;
public interface MyService {
    boolean process();
}

package my.app.core.impl
@Service
public class MyServiceImpl implements MyService {

    @Override
    public boolean process() {
        // do something cool...
    }
}

package my.app.somewhere.else.impl
@Service
@Transactional
public class TransactionalMyServiceImpl implements MyService {

    @Autowire
    private MyService myService;

    @Override
    public boolean process() {
        myService.process();
    }
}

Is it possible or do I need to @Autowire explicitly MyServiceImpl instead of interface? Which means to add maven dependancy to my.app.somewhere.else.impl.pom.

Upvotes: 1

Views: 85

Answers (1)

starman1979
starman1979

Reputation: 1084

You can give different names to your services like so:

@Service
@Qualifier("transactionalMyService")

And then when you autowire you can use the name:

@Autowired
@Qualifier("transactionalMyService")
private MyService myService;

Upvotes: 5

Related Questions