使用类似于 Spring 的 Guice 将属性注入 类,例如 VelocityEngineFactoryBean
Injecting properties into classes like VelocityEngineFactoryBean using Guice similar to Spring
我正在尝试使用 Guice 在我的代码中注入 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>
Class VelocityEngineFactoryBean 没有此 属性 和 @Inject 注释。
public class VelocityEngineFactoryBean extends VelocityEngineFactory
implements FactoryBean<VelocityEngine>, InitializingBean, ResourceLoaderAware {
private VelocityEngine velocityEngine;
它也没有为此提供 setter。
- 那么如何使用 Guice 在我的代码中注入这些对象呢?
- 一般来说,如何创建这种类型的对象并在代码中使用它?
这就是我实现它的方式。
- 围绕 apache VelocityEngine 编写自定义包装器,而不是使用 VelocityEngineFactoryBean。
- 使用提供程序将它们注入 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 会注入 VelocityEngine。
如果我想使用 VelocityEngineFactoryBean,还有另一种方法可以使用 reflection and Provides
创建 VelocityEngineFactoryBean 的实例。
然而,这看起来更像是一个 hack,所以我想我会直接创建一个 Apache 引擎的实例而不是使用 Spring.
我正在尝试使用 Guice 在我的代码中注入 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>
Class VelocityEngineFactoryBean 没有此 属性 和 @Inject 注释。
public class VelocityEngineFactoryBean extends VelocityEngineFactory
implements FactoryBean<VelocityEngine>, InitializingBean, ResourceLoaderAware {
private VelocityEngine velocityEngine;
它也没有为此提供 setter。
- 那么如何使用 Guice 在我的代码中注入这些对象呢?
- 一般来说,如何创建这种类型的对象并在代码中使用它?
这就是我实现它的方式。
- 围绕 apache VelocityEngine 编写自定义包装器,而不是使用 VelocityEngineFactoryBean。
- 使用提供程序将它们注入 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 会注入 VelocityEngine。
如果我想使用 VelocityEngineFactoryBean,还有另一种方法可以使用 reflection and Provides
创建 VelocityEngineFactoryBean 的实例。
然而,这看起来更像是一个 hack,所以我想我会直接创建一个 Apache 引擎的实例而不是使用 Spring.