My application has a class called Gateway and a json file with a set of these gateways. I already parsed this json, giving me a Set object. Now I want to create a Multibinder to inject this set throughout my code. So far, I've created this provider:
public class GatewaysProvider implements Provider<Set<Gateway>> {
@Override
public Set<Gateway> get() {
try {
File file = new File(getClass().getResource("/gateways.json").toURI());
Type listType = new TypeToken<Set<Gateway>>(){}.getType();
return new Gson().fromJson(new FileReader(file), listType);
} catch (URISyntaxException | FileNotFoundException e) {
e.printStackTrace();
}
return new HashSet<>();
}
}
What more should I do to be able to inject this set anywhere in my code, like this:
Set<Gateways> gateways;
@Inject
public AppRunner(Set<Gateway> gateways) {
this.gateways = gateways;
}
What you need is the implementation of dependency injection mechanism.
You can do it yourself, but I'd suggest you to use existent DI library, like EasyDI
Please proceed, with steps below:
Add EasyDI to your classpath. With Maven it would be:
<dependency>
<groupId>eu.lestard</groupId>
<artifactId>easy-di</artifactId>
<version>0.3.0</version>
</dependency>
Add wrapper type for your Gateway set, and adjust Provider correspondingly:
public class GatewayContainer {
Set<Gateway> gateways;
public void setGateways(Set<Gateway> gateways) {
this.gateways = gateways;
}
}
public class GatewayProvider implements Provider<GatewayContainer> {
@Override
public GatewayContainer get() {
try {
File file = new File(getClass().getResource("/gateways.json").toURI());
Type listType = new TypeToken<Set<Gateway>>() {
}.getType();
Set<Gateway> set = new Gson().fromJson(new FileReader(file), listType);
GatewayContainer container = new GatewayContainer();
container.setGateways(set);
return container;
} catch (URISyntaxException | FileNotFoundException e) {
e.printStackTrace();
}
return new GatewayContainer();
}
}
Configure and use your context:
public class AppRunner {
GatewayContainer container;
public AppRunner(GatewayContainer container) {
this.container = container;
}
public static void main(String[] args) {
EasyDI context = new EasyDI();
context.bindProvider(GatewayContainer.class, new GatewayProvider());
final AppRunner runner = context.getInstance(AppRunner.class);
}
}
Afterwards, you will get the AppRunner with all the injected dependencies.
Note: There is no usage of any sort of @Inject
(or similar) annotation, because EasyDI not requires it by default