I writing a library which doesn't have a main
and isn't a Spring Boot
application but I'd still like to use Spring Framework's dependency injection to load the dependencies of my classes. I'd like this library to be available to everyone, even developers who aren't going to be using Spring.
Is there a way for me to take advantage of Spring Framework's dependency injection even if the users of my library won't be using Spring?
Currently I'm importing my library into another one of my apps but my dependencies are turning out as null
. Is there a way to get around this?
@Component
public class Client
{
@Autowired
private ClientService clientService; // this is null
public static Client createClientWithCredentials(String clientId, String clientSecret)
{
return new Client(clientId, clientSecret);
}
private Client(String clientId, String clientSecret)
{
// ...
}
}
@Service
public class ClientService {
// ...
}
Someone using my library would use instantiate it like this.
...
// Non-Spring project
Client client = Client.createClientWithCredentials("id", "secret");
...
Unfortunately using client
will at some point throw a NullPointerException
since clientService
is null
. I'm also testing my app this way and this is why I know that I have null
dependencies.
How can I take advantage of Spring's Dependency Injection if my app is never run but only used as a library?
Is this possible or do I need to use the old way of every class constructing it's own dependencies?