Вот фрагмент кода, который показывает, как внедрить объект контекста, свойства конфигурации и путь к классам.
Service parse(
String dslFile, List<String> classpath,
Map<String, Object> properties, ServiceContext context) {
// add POJO base class, and classpath
CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass( BaseDslScript.class.getName() );
cc.setClasspathList(classpath);
// inject default imports
ic = new ImportCustomizer();
ic.addImports( ServiceUtils.class.getName() );
cc.addCompilationCustomizers(ic);
// inject context and properties
Binding binding = new Binding();
binding.setVariable("context", context);
for (prop: properties.entrySet()) {
binding.setVariable( prop.getKey(), prop.getValue());
}
// parse the recipe text file
ClassLoader classloader = this.class.getClassLoader();
GroovyShell gs = new GroovyShell(classloader, binding, cc);
FileReader reader = new FileReader(dslFile);
try {
return (Service) gs.evaluate(reader);
} finally {
reader.close();
}
Обратите внимание, что этот код также внедряет базовый класс, чтобы получить детальный контроль при разборе свойств и поддержку наследования между различными файлами DSL.
Для получения дополнительной информации и рабочего исходного кода из проекта Cloudify см.
http://cloudifysource.tumblr.com/post/23046765169/parsing-complex-dsls-using-groovy