MentaContainer is a straightforward yet powerful and complete IoC container. It supports IoC, DI and Auto-wiring through a simple API.
Inversion of Control: (IoC)
public interface Logger { // contract methods } public class FileLogger implements Logger { // methods implementation } // the regular way: Logger logger = new FileLogger(); // inversion of control: Container c = new MentaContainer(); // starting up the container c.ioc(Logger.class, FileLogger.class); // choosing an implementation Logger logger = c.get(Logger.class); // requesting an instance
Things to note:
Logger.class
as the key for the FileLogger.class
component. You can use any object as a key and the toString()
method will be called to get a string representation of the key. You can also use strings like below:c.ioc("myLogger", FileLogger.class); Logger logger = c.get("myLogger"); // actually if you pass a class object like Logger.class, the container // gets its simple name with the first letter lower-case instead of calling toString() c.ioc(Logger.class, FileLogger.class); // is the same things as: c.ioc("logger", FileLogger.class); // matches a "logger" property during auto-wiring, just in case ;)
Dependency Injection: (DI)
public interface LoggerDAO { // contract methods } public class JdbcLoggerDAO implements LoggerDAO { // methods implementation } public class DatabaseLogger implements Logger { private final LoggerDAO loggerDAO; // DatabaseLogger depends on LoggerDAO public DatabaseLogger(LoggerDAO loggerDAO) { this.loggerDAO = loggerDAO; } // methods implementation } Container c = new MentaContainer(); c.ioc(LoggerDAO.class, JdbcLoggerDAO.class); c.ioc(Logger.class, DatabaseLogger.class).addConstructorDependency(LoggerDAO.class); Logger logger = c.get(Logger.class); // Logger will come with its dependency LoggerDAO
Things to note:
LoggerDAO.class
will come from the container so it must have been defined in the container (line 21).addPropertyDependency(Object key)
method.Auto-Wiring:
If you have many objects with the same dependency, you can just use auto-wiring instead of specifying the same dependency for each one of them. See the example below:
c.ioc(LoggerDAO.class, JdbcLoggerDAO.class); c.autowire(LoggerDAO.class); c.ioc(Logger.class, DatabaseLogger.class);
Things to note:
LoggerDAO.class
dependency of DatabaseLogger
(line 3). Everything that needs a LoggerDAO
will receive one through auto-wiring.