Yurii Bondarenko
Yurii Bondarenko

Reputation: 3550

Add to spring an interface implementation from another jar

I have a "core" module which have an interface "DbService". The implementation of that interface is inside another module "MsSqlDbService" (for different purposes I have many implementation of "DbService", so I just place "right" jar in the "right" place before running my program)

To load "DbService" I use standard java service loader java.util.ServiceLoader<DbService>

So I wonder: is there a way to make my spring container manage "DbService"? Because now the spring container manages for me the class which actually loads implementation of "DbService", instead of managing "DbService" itself.

Upvotes: 0

Views: 2179

Answers (2)

John R
John R

Reputation: 2106

(for different purposes I have many implementation of "DbService", so I just place "right" jar in the "right" place before running my program)

If I understand correctly, you have multiple JARs that all contain implementations of the same interface. You want Spring to pickup whichever one is on the classpath at deployment time and then autowire everything together correctly?

Spring can definitely be used as a "poor man's plugin framework" to accomplish this sort of thing:

1) In your main project, add this to your context:

<import resource="classpath:applicationContext-dbService.xml"/>

2) In each JAR, create a file named applicationContext-dbService.xml. It would look something like this for the SQL Server example you provided.

<bean id="msSqlDbService" class="com.foo.MsSqlDbServiceImpl"/>

3) When your main context is loaded, Spring will scan the classpath for files named applicationContext-dbService.xml and then process any beans that are defined in them. Assuming that you only have one "plugin" JAR on the classpath at deployment time, you'll be able to autowire an instance of DbService into anything in your main project.

Upvotes: 1

Pradeep Kr Kaushal
Pradeep Kr Kaushal

Reputation: 1546

You can define the DbService interface as the member of the class.

class Demo{

@Autowired
@Qualifier("msSqlDbService")
private DbService dbService;

//Setter and getter
}

Now put the implementation classes(which you require) of DbService in spring xml config

<bean id="msSqlDbService" class="xxxx.MsSqlDbService"/>//xxxx is the package name.

Upvotes: 0

Related Questions