[英]Should I use Spring to configure my XML parser?
I have the following boilerplate code in my application. 我的应用程序中包含以下样板代码。 It's likely to be repeated in several different objects involving with parsing objects of different kinds: 它可能会在涉及解析不同类型对象的几个不同对象中重复:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
AssetTOSaxHandler handler = new AssetTOSaxHandler();
parser.parse( assetStream, handler );
return handler;
Since the handler
object is stateful I think "new" is the best way to obtain that, but it occured to me that factory
and parser
are probably re-usable objects that I might be able to inject into my objects instead to achieve cleaner code. 由于handler
对象是有状态的,因此我认为“新”是获得此状态的最佳方法,但是在我看来, factory
和parser
可能是可重用的对象,我也许可以将它们注入到我的对象中,从而获得更简洁的代码。
Did you do this? 你做了这个了吗? Is that useful? 那有用吗? What frameworks and syntax did you use? 您使用了什么框架和语法?
If the choice of parser is a cross-cutting concern and you are going to use it in multiple locations I'd define the parser factory in one location and inject the factory to those objects that use it. 如果解析器的选择是一个跨领域的问题,并且您打算在多个位置使用它,那么我将在一个位置定义解析器工厂,并将工厂注入使用它们的对象。 Moreover, I would not want to have to change each user of the SAX parser because the factory changes. 而且,由于工厂发生了变化,我不想更改SAX解析器的每个用户。 I'd rather have them change if their task changes. 如果他们的任务改变了,我宁愿让他们改变。
I've been using Spring in a couple of projects but I've been rather unsatisfied with all the magic that's going around. 我已经在几个项目中使用过Spring,但是对于周围发生的所有魔术我还是不满意。 Currently I'm looking more into Guice which seems more attractive in my eyes when it comes to dependency injection. 目前,我正在研究Guice ,它在依赖注入方面似乎更具吸引力。 If you use Spring to provide other services by all means do. 如果您使用Spring一定要提供其他服务。 Furthermore, Guice and Spring can be combined . 此外, Guice和Spring可以结合使用 。
The injection would go something like this 注射会像这样
public class Example{
@Inject
private SAXParser parser;
...
AssetToSaxHandler createHandlerFor(final InputStream assetStream) {
AssetTOSaxHandler handler = new AssetTOSaxHandler();
parser.parse(assetStream, handler);
return handler;
}
}
Then you would have a Guice module where you declare the binding 然后,您将有一个Guice模块,在其中声明绑定
public class ParserModule extends AbstractModule {
@Override
public void configure() {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
bind(SaxParser.class).toInstance(factory.newSAXParser());
}
}
And in your initializing class you'd call Guice.createInjector(new ParserModule(),...)
在初始化类中,您将调用Guice.createInjector(new ParserModule(),...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.