我正在尝试使用Guice在我的代码中注入(inject)org.springframework.ui.velocity.VelocityEngineFactoryBean的实例。但不确定如何指定此 Bean 的属性 velocityProperties。
目前在 Spring 中,我可以使用它。
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">class</prop>
<prop key="class.resource.loader.class">
org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</prop>
</props>
</property>
</bean>
类 VelocityEngineFactoryBean 没有带有 @Inject 注释的此属性。
public class VelocityEngineFactoryBean extends VelocityEngineFactory
implements FactoryBean<VelocityEngine>, InitializingBean, ResourceLoaderAware {
private VelocityEngine velocityEngine;
它也没有为此提供 setter 。
- 那么如何使用 Guice 在我的代码中注入(inject)这样的对象呢?
- 一般来说,如何创建这种类型的对象并在代码中使用它?
最佳答案
这就是我实现它的方式。
- 围绕 apache VelocityEngine 编写自定义包装器,而不是使用 VelocityEngineFactoryBean。
- 使用提供程序将它们注入(inject) Guice。
这有效。
@Provides
VelocityEngine velocityEngine() throws Exception {
Properties props = new Properties();
props.put("resource.loader", "class");
props.put("class.resource.loader.class", ClasspathResourceLoader.class.getName());
return new VelocityEngine(props);
}
Guice 会注入(inject) VelocityEngine。
如果我想使用VelocityEngineFactoryBean,还有另一种方法,即使用reflection 和 Provides
创建 VelocityEngineFactoryBean 的实例。
然而,这看起来更像是一种 hack,所以我想直接创建 Apache 引擎的实例,而不是使用 Spring。
关于java - 使用类似于 Spring 的 Guice 将属性注入(inject)到像 VelocityEngineFactoryBean 这样的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766422/