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.
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. 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. Currently I'm looking more into Guice which seems more attractive in my eyes when it comes to dependency injection. If you use Spring to provide other services by all means do. Furthermore, Guice and Spring can be combined.
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
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(),...)
精彩评论