Give me a demo of how to use google guice dependency injection, including complete steps
Google Guice is a lightweight dependency injection framework for Java that helps manage dependencies in your application. Below is a step-by-step guide to using Google Guice for dependency injection, including a simple example.
Create a new Java project: You can use any IDE (like IntelliJ IDEA, Eclipse, or even a simple text editor) to create a new Java project.
Add Guice Dependency: If you are using Maven, add the following dependency to your pom.xml
:
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>5.0.1</version> <!-- Check for the latest version -->
</dependency>
If you are not using Maven, download the Guice JAR file from the Maven Repository and add it to your project's classpath.
Let's create a simple example with a Car
class and an Engine
class. The Car
class will depend on the Engine
class.
Create the Engine
interface:
public interface Engine {
void start();
}
Create a concrete implementation of the Engine
interface:
public class V8Engine implements Engine {
@Override
public void start() {
System.out.println("V8 Engine started.");
}
}
Create the Car
class that depends on the Engine
:
public class Car {
private final Engine engine;
@Inject // This annotation tells Guice to inject the dependency
public Car(Engine engine) {
this.engine = engine;
}
public void drive() {
engine.start();
System.out.println("Car is driving.");
}
}
A Guice module is where you configure the bindings between interfaces and their implementations.
Create a module class:
import com.google.inject.AbstractModule;
public class CarModule extends AbstractModule {
@Override
protected void configure() {
bind(Engine.class).to(V8Engine.class); // Bind Engine to V8Engine
}
}
Now, create a main class to run your application and use Guice to inject the dependencies.
Create the main class:
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Main {
public static void main(String[] args) {
// Create the Guice injector with the CarModule
Injector injector = Guice.createInjector(new CarModule());
// Get an instance of Car with dependencies injected
Car car = injector.getInstance(Car.class);
// Use the Car instance
car.drive();
}
}
Compile and run your application. You should see the following output:
V8 Engine started.
Car is driving.
In this example, we demonstrated how to use Google Guice for dependency injection in a simple Java application. The key steps included:
This is a basic introduction to Google Guice. As you build more complex applications, you can explore advanced features like scopes, provider methods, and more.