Reputation: 13
I'm new to dependency injection. It seems I have a good understanding of it, but I am getting a little bit confused about one thing. Suppose I have a bean:
@Bean
HttpClient {
public void void POST(String url, Object payload) {
.......
}
}
And have a class using that bean:
Message {
public void send() {
httpClient.POST(this);
}
}
Obviously I should just inject the HttpCLient into the Message.But.... The Message also has a constructor with params:
Message {
private final String text;
public Message(String text) {
this.text = text;
}
public void send() {
httpClient.POST(this);
}
}
And it will be used in such way:
SomeClient {
if(....) {
new Message("Case 1 text").send();
} else {
new Message("Case 2 text").send();
}
}
Thus the Message is an immutable object that is used per request with new constructor's params and in the same time it needs the heavyweight HttpClient to be inject.
Maybe this example is not quite correct, but I believe there is many similar issues you had come across.
So the question is: what should I do if I have to instantiate objects by hands but they require dependencies to be inject?
Upvotes: 1
Views: 974
Reputation: 7744
Propagating dependencies is usually solved with Factories. You don't directly instantiate the Message
, you use a Factory
to do it, like this:
messageFactory.createMessage("Text").send();
With the message factory being:
public interface MessageFactory {
Message createMessage(String text);
}
And then the dependency to the HTTP Client is in the actual factory:
public final class HttpClientBasedMessageFactory {
private final HttpClient httpClient;
...
@Override
public Message createMessage(String text) {
return new Message(httpClient, text);
}
}
That is now without any dependency injection "framework", but it can be adjusted to support whatever you are using.
Upvotes: 1