我正在尝试让 Spring 初始化和缓存 Freemarker 的配置实例,以便在我的 Restlet 应用程序中使用。问题是它ContextTemplateLoader
需要一个类型的参数,该参数org.restlet.Context
可通过getContext()
应用程序中的方法调用访问。如何在 Restlet 是“主容器”的 Spring 容器“内部”访问此上下文(即,这是一个使用 spring 而不是反之亦然的 restlet 应用程序)?
现在这是我缓存 freemarker 配置的方式:
public class HelloWorldComponent extends Component {
//Cache freemarkerConfiguration
private static Configuration freemarkerConfiguration;
public HelloWorldComponent()
{
freemarkerConfiguration = new Configuration();
// Must pass getContext() as argument - prevents 'springification?'
ContextTemplateLoader loader = new ContextTemplateLoader(getContext(), "war:///WEB-INF");
freemarkerConfiguration.setTemplateLoader(loader);
/* All other beans created and cached by loading the SpringContext */
SpringContext springContext = new SpringContext(getContext());
springContext.getXmlConfigRefs().add("war:///WEB-INF/applicationContext.xml");
getServers().add(Protocol.HTTP);
this.getDefaultHost().attach(new HelloWorldApplication());
}
public static Configuration getFreemarkerConfiguration()
{
return freemarkerConfiguration;
}
我个人更喜欢让 Spring 本身可以缓存 freemarker 配置,但ContextTemplateLoader
需要 aContext
并且这在应用程序之外是不可访问的。拥有一个静态方法似乎是一种 hack。
让spring实例化freemarker配置的最简单/最简单/最干净的方法是什么?
原因:在每次访问模板之前加载配置是没有意义的,最好缓存它。如果这可以在 Spring 本身中定义并且 IoC 只是在其中实例化,那就太好了org.restlet.Component
似乎有一个静态方法Context.getCurrent()
可用于获取当前上下文,但我不知道如何通过 spring 调用它(如果有的话)。我对拥有 Spring MVC 库等只是为了创建一个 freemarker 配置实例不感兴趣(有办法做到这一点,但我不想要 Spring 相关的 servlet 等)