在 spring 4 应用程序中,我创建了两个 bean,如下所示:
<!-- schemaFactory-->
<bean id="schemaFact" class="javax.xml.validation.SchemaFactory"
factory-method="newInstance">
<constructor-arg value="http://www.w3.org/2001/XMLSchema" />
</bean>
<!-- schema -->
<bean id="schema" class="javax.xml.validation.Schema"
factory-bean="schemaFact" factory-method="newSchema">
<constructor-arg value="classpath:/configs/sample.xsd" />
</bean>
一个生成模式工厂,另一个使用该工厂(根据 xsd 验证 xml)。
在代码中:
public class example {
@Inject
private Schema aschema;
......
private validate(){
Validator validator = aschema.newValidator();
validator.validate(xmlFile);
}
}
这工作正常,但我想知道是否可以以不需要单独定义工厂 bean 的方式编写这个 spring.xml
(并在最后有一个更简单的 spring.xml
)。正如您所看到的,我只需要将 schema
bean 注入(inject)到我的 example
类中,而根本不需要 schemaFact
。
最佳答案
无论您是否直接使用它们,注入(inject)的依赖项都必须Spring bean。
因此,即使您没有直接在代码中使用 SchemaFactory
而是将其作为依赖项注入(inject)到另一个 spring bean 中,两者都必须是 spring 管理的 bean
你可以考虑使用注解,那么你就根本不需要 spring 文件了。
关于java - 在 spring 中定义 bean 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33971844/