最近有空試用了一下Guice,感覺還是比較小巧的,在上面做了個類似Tapestry的Configuration,利用它可以實作類似擴充點的功能。 (可以參考http://tapestry.apache.org/tapestry5/tapestry- ioc/configuration.html)
另外關于網上代碼和XML的配置的問題,個人認為不是問題。基于代碼的配置就象一個核,如果你喜歡基于XML的配置,隻要自己寫一個子產品,讀取XML并使用其中的資訊再用基于代碼的配置去配置即可,隻是基于使用@Inject Annotation 的地方稍微難處理點,但也隻需要動态生成類也可以解決這個問題。
使用的時候參考以下這個測試用例:
public class GuiceTest extends TestCase {
public static class ContributorUsingContributorClass extends
ContributableModule {
@Override
protected void configure() {
contribute(new AbstractContributor() {
@Inject
@ConfigFor(AnotherInterface.class)
OrderedConfiguration<String> orderedConfiguration;
@Inject
@ConfigFor(AnotherInterface.class)
Configuration<String> unorderedConfiguration;
@Inject
@ConfigFor(Service.class)
MappedConfiguration<String, Runnable> configuration;
@Inject
public void contribute() {
configuration.add("abcd", new Runnable() {
public void run() {
}
});
unorderedConfiguration.add("abc");
orderedConfiguration.add("my", "abc");
}
});
}
}
public void testClient() {
Injector injector = Guice.createInjector(new MyModule());
Client client = injector.getInstance(Client.class);
MockService mock = (MockService) injector.getInstance(Service.class);
client.go();
assertTrue(mock.isGone());
}
public void testConfigurationThroughContributorClass() {
Injector injector = Guice.createInjector(new MyModule(),
new ContributorUsingContributorClass());
MockService mock = (MockService) injector.getInstance(Service.class);
Map<String, Runnable> map = mock.getConfigMap();
assertNotNull(map);
assertEquals(1, map.size());
}
public void testUnorderedConfiguration() {
Injector injector = Guice.createInjector(new MyModule(),
new ContributorUsingContributorClass());
MockService mock = (MockService) injector.getInstance(Service.class);
Collection<String> config = mock.config;
assertNotNull(config);
assertEquals(1, config.size());
assertEquals("[abc]", config.toString());
}
public void testOrderedConfiguration() {
Injector injector = Guice.createInjector(new MyModule(),
new ContributorUsingContributorClass());
MockService mock = (MockService) injector.getInstance(Service.class);
Collection<String> config = mock.orderedConfig;
assertNotNull(config);
assertEquals(1, config.size());
assertEquals("[abc]", config.toString());
}