Reputation: 527
I want to create an java API to connect to a Restful API. To deal with dependencies, I want to use Spring.
However, all examples I see over the internet talks about a DI container, and the whole system is running like a service.
What I need is: Provide some classes to user be able to connect to such Restful API, but the inner dependencies of these classes being resolved by Spring. Needless to say that this framework won't start any application server. It will just provide some useful classes and interfaces to contact the RestAPI.
Is that possible?
Thanks in advance!
Upvotes: 1
Views: 1435
Reputation: 38300
The Situation
Let's suppose I've wrote an API which provides a class called Car. User can use this Car class in their project. But Car class depends on two other classes: Wheel and Engine. What I want is the last two classes to be injected automatically, without the user needing to instantiate this.
The short answer to the situation is: no. The reason for this is somebody must start Spring. You have some options.
You can create some kind of initialization class that starts Spring for you. The API user would need to do this:
myAPI.initialize();
.A giant (imho) drawback of this is that every class in your API would need to check to see if initialization happened.
Expose your classes via a factory. In this case, the API user would do something like this: MyFactory.createCar(...parameters...);
With this technique, the Spring initialization would be hidden from the user because you could load Spring in a static initialization block in the MyFactory class.
Instead of a factory patter, use a builder pattern to instantiate your classes. This is, effectively, a variation of the factory solution, except that each Builder would call a static initialization method of some hidden (perhaps package access) class that starts Spring once.
If you only want DI, Spring may not be a good fit for you (it might be overkill). Google guice is a "just" DI tool that might be a good fit. Even with guice, somebody will still need to start it, so solutions 1-3 will apply.
Upvotes: 1