Java Spring - Inject a parameter into a superclass with annotations
dependency-injection, inheritance, java, spring, superclass
Solution
If `urlBuilder` is required for `JsonConnection` you can pass it as a constuctor argument and use constructor injection:
public class JsonConnection{
private UrlBuilder urlBuilder;
public JsonConnection(UrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
}
@Component
public class FacebookJsonConnection extends JsonConnection {
private UrlBuilder urlBuilderFacebook;
@Inject
public FacebookJsonConnection(UrlBuilder urlBuilderFacebook) {
super(urlBuilderFacebook);
this.urlBuilderFacebook = urlBuilderFacebook;
}
}
Problem
I have a superclass that needs the subclass to provide the implementation of the interface that the superclass runs against. We use Spring and DI so we can't just create the implementation with new. The subclass will know which bean to provide only after Spring is initialized so using a super constructor won't work. I also don't want to use q `@PostConstruct` setup method in the subclass as that requires the subclass developer to know how to set up the superclass. I want the superclass to demand the subclass to provide the reference to the implementing bean so that it can setup its member: The superclass uses the UrlBuilder Interface: ``` public class JsonConnection{ private UrlBuilder urlBuilder; } ``` the subclass provides the implementation (`UrlBuilderFacebook`) via dependency injection. ``` @Component public class FacebookJsonConnection extends JsonConnection { @Inject private UrlBuilder urlBuilderFacebook; } ``` the superclass can be abstract or a component, it doesn't matter. What matters is that I want to be able to create lightweight subclasses that provide the `UrlBuilder` to the superclass and `@Inject` them where needed. ``` @Inject private JsonConnection facebookJsonConnection; ``` or ``` @Inject private JsonConnection redmineJsonConnection; ``` Also I don't want the superclass to know anything about which subclass is using it.