Skip to content

Instantly share code, notes, and snippets.

@MichalBrylka
Created December 1, 2021 21:38
Show Gist options
  • Save MichalBrylka/d50396b6652a56e94e15b88e467df922 to your computer and use it in GitHub Desktop.
Save MichalBrylka/d50396b6652a56e94e15b88e467df922 to your computer and use it in GitHub Desktop.
Java Guice Ioc
package corp;
import com.google.inject.*;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Module());
Phone phone = injector.getInstance(Phone.class);
}
}
class Contact {
}
interface Contacts {
Iterable<Contact> findByName(String name);
}
class SimCard implements Contacts {
public Iterable<Contact> findByName(String name) {
return Collections.emptyList();
}
}
interface PhoneBase {
}
class Phone implements PhoneBase {
Contacts contacts;
@Inject
public Phone(Contacts contacts) {
this.contacts = contacts;
}
}
class Module extends AbstractModule {
@Override
protected void configure() {
bind(Contacts.class).to(SimCard.class);
bind(PhoneBase.class).to(Phone.class);
//install(new XmlBeanModule(xmlUrl));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>IocTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>5.0.1</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment