今まで使ったDIフレームワークと比べても,コードを簡潔に短くことが出来るようになったと思う.
以下の例はFTPでファイルを送信するロジックを仮実装した例.コンフィグのバインドの例は決して真似をせぬ様.あくまでguiceの基本バインドの例である.
FileTransmit.java
ackage org.tanuneko;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class FileTransmit {
public static void main(String args[]) {
String[] myArgs = {"/home/neko32", "tako.log", "640"};
Config c = new AppConfig(myArgs);
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(FileSenderIF.class).to(FTPFileSender.class);
bind(Config.class).toInstance(c);
}
});
FileTransmitProgram ft = injector.getInstance(FileTransmitProgram.class);
ft.run();
}
class MyAppConfig extends Config {
MyAppConfig(String[] args) {
// do not do this in product code
super.logFileLocation = args[0];
super.logFileName = args[1];
super.maxFileSize = Integer.parseInt(args[2]);
}
}
}
FileTransmitProgram.java
package org.tanuneko;
import com.google.inject.Inject;
public class FileTransmitProgram {
@Inject
private FileSenderIF sender;
@Inject
private Config conf;
public void run() {
sender.setLogging(conf.getLogFileLocation(), conf.getLogFileName());
sender.setFileMaxFileSize(conf.getMaxFileSize());
sender.send("ABC", "DATA");
}
}
FTPFileSender.java
package org.tanuneko;
public class FTPFileSender implements FileSenderIF {
private int maxFileSize = -1;
public void setLogging(String logLocation, String fileName) {
System.out.println(String.format("Setting logs[%s/%s]", logLocation, fileName));
}
public void setFileMaxFileSize(int maxFileSize) {
int prevMax = maxFileSize;
this.maxFileSize = maxFileSize;
System.out.println(String.format("max file size has changed from %d to %d", prevMax, this.maxFileSize));
}
@Override
public void send(String fileName, String data) {
System.out.println(String.format("file %s(%s) was sent via FTP", fileName, data));
}
}