Skip to content

Dependency Injection

Thomas Cashman edited this page Aug 16, 2013 · 1 revision

This tutorial shows how to use mini2Dx's dependency injection API. Both Singleton and Prototype auto-wiring are supported.

Basic Dependency Injection

The GameContext classes provides methods to scan for singletons and prototypes and auto-wired dependencies accordingly. In the example below, the developer has defined a Camera class which requires a Player instance to be auto-wired in. The Player class is annotated with @Singleton meaning any class that depends on it will share the same instance of Player.

package com.mygame.engine;

import org.mini2Dx.injection.Autowired;
import org.mini2Dx.injection.Prototype;

@Prototype
public class Camera {
		@Autowired
		private Player player;

		...
}
package com.mygame.entities;

import org.mini2Dx.injection.Singleton;

@Singleton
public class Player {
		private int x;
		private int y;

		...
}

Both classes are part of the com.mygame package so this will be the package scanned (recursively) using the GameContext class.

GameContext.initialise(new String[] { "com.mygame" });

All singletons and prototypes are wired up now. To retrieve the wired instances, simply query the game context.

Player player = GameContext.getBean(Player.class); //Always returns the same instance
Camera camera = GameContext.getBean(Camera.class); //Always returns a new instance correctly wired up

Hot-swapping implementations

The benefit of using dependency injection is that by using interfaces, implementations can be hot-swapped. In the example below the developer has made an interface for input handling. The Player class required an implementation of InputHandler to be autowired in.

public interface InputHandler {
		public void handleButtonPress(int keycode);
}
public class Player {
		@Autowired
		private InputHandler inputHandler;

		private int x;
		private int y;

		...
}

The developer can now use a desktop-specific implementation of this interface in their desktop application.

public class DesktopInputHandler implements InputHandler {
		public void handleButtonPress(int keycode) {
				//Desktop specific code here
		}
}

Likewise, Android-specific version can be implementation inside their Android application.

public class AndroidInputHandler implements InputHandler {
		public void handleButtonPress(int keycode) {
				//Android specific code here
		}
}

Clone this wiki locally