API / Apache Velocity Interview questions
How do you configure a custom template ResourceLoader in Velocity?
Implement Velocity's ResourceLoader abstract class, overriding the methods that locate a resource's InputStream and detect whether it's changed since it was cached, then register the implementation by class name in the engine properties.
public class DbResourceLoader extends ResourceLoader { public InputStream getResourceStream(String name) { // fetch template text from a database row by name return new ByteArrayInputStream(fetchTemplateBytes(name)); } public boolean isSourceModified(Resource resource) { return true; } public long getLastModified(Resource resource) { return 0; } }
Properties p = new Properties(); p.setProperty("resource.loader", "db"); p.setProperty("db.resource.loader.class", "com.example.DbResourceLoader"); VelocityEngine engine = new VelocityEngine(p); engine.init();
This pattern is what lets teams store templates in a database or a CMS instead of on disk, letting non-developers edit templates through an admin UI without redeploying the application, while the rest of Velocity's engine, parsing, caching, rendering, behaves exactly the same regardless of where the bytes came from.
More Related questions...