
links
Javaเร็วส์, Javascript, Erlang, Python, Ruby, Clojure, Groovy, เลี้ยงลูก, วาดภาพ
public interface UploadService {
public void upload(InputStream input, String type);
}
public class UploadServiceImpl implements UploadService {
private IndexService indexService;
private RepositoryService repositoryService;
private Map<String, Parser> parserMap = new HashMap<String, Parser>();
public void upload(InputStream input, String type) {
Parser parser = parserMap.get(type);
Document document = parser.parse(input);
Long key = repositoryService.persistent(document);
indexService.index(document, key);
}
public void setIndexService(IndexService indexService) {
this.indexService = indexService;
}
public void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
public void setParserMap(Map<String, Parser> parserMap) {
this.parserMap = parserMap;
}
}
<beans>
<bean id="indexService" class="test.service.impl.IndexServiceImpl"/>
<bean id="repositoryService" class="test.service.impl.RepositoryServiceImpl"/>
<bean id="uploadService" class="test.service.impl.UploadServiceImpl">
<property name="indexService" ref="indexService"/>
<property name="repositoryService" ref="repositoryService"/>
<property name="parserMap">
<map>
<entry>
<key><value>pdf</value></key>
<bean class="test.service.impl.PdfParser"/>
</entry>
<entry>
<key><value>word</value></key>
<bean class="test.service.impl.MsWordParser"/>
</entry>
</map>
</property>
</bean>
</beans>
public class MyAppModule {
/**
* bind ใช้กับกรณีพวก simple bean, ไม่ต้องมีอะไรให้ set มากมาย
*/
public static void bind(ServiceBinder binder) {
binder.bind(RepositoryService.class, RepositoryServiceImpl.class);
binder.bind(IndexService.class, IndexServiceImpl.class);
}
/**
* กรณีพวก bean ที่ซับซ้อนมากขึ้น ก็ให้ตั้งชื่อ method ว่า build นำหน้า
* แล้วก็กำหนด parameter ตาม dependency ที่ต้องการ
* โดยลำดับจะเป็นอะไรก่อนหลังก็ได้
*/
public static UploadService buildUploadService(
IndexService indexer,
RepositoryService repositoryService,
Map<String, Parser> configuration) {
UploadServiceImpl impl = new UploadServiceImpl();
impl.setIndexService(indexer);
impl.setRepositoryService(repositoryService);
impl.setParserMap(configuration);
return impl;
}
/**
* ตรงนี้แหล่ะที่ tapestry5 IoC ยังเหนือกว่า Spring
* เราสามารถกำหนด contribute ที่ทำหน้าที่ provide configuration ให้กับ builder ข้างบน
* โดย contribute method สามารถ plugin เข้ามาจาก module อื่นๆได้
* ทำให้มันมีลักษณะเป็น modular มากกว่า spring
*/
public static void contributeUploadService(MappedConfiguration<String, Parser> configuration) {
configuration.add("pdf", new PdfParser());
configuration.add("word", new MsWordParser());
}
}
public void run() {
RegistryBuilder builder = new RegistryBuilder();
builder.add(MyAppModule.class, ParserModule.class);
Registry registry = builder.build();
UploadService service = registry.getService(UploadService.class);
service.upload(null, "pdf");
}