2011-12-22 56 views
2

我想将xml文件加载到spring bean中作进一步处理。我知道可以加载properties文件,只需在spring配置文件中定义一个bean属性即可。有没有可能对xml文件做同样的事情?在弹簧中加载xml文件

编辑 例如,我想有一个bean:

public class Bean { 
    private File file 
    public void setFile(File file) { 
     this.file = file 
    } 
    //.... 
} 

,并在我的配置文件我想设置这样的:

<bean id="bean" class="blabla.Bean"> 
    <property name="file" value="smth here"/> 
</bean> 

,然后我想解析使用DOM的xml

+0

可能重复(http://stackoverflow.com/questions/479855/is-there-a-propertyplaceholderconfigurer-like-class-for-use-spring-that-acc) – CoolBeans

+0

另请参阅[PropertyPlaceholderConfigurer从XML文件读取(Apache Commons配置)](http://stackoverflow.com/问题/ 3163838/propertyplaceholderconfigurer-reads-from-xml-file-apache-commons-configuration) – CoolBeans

+0

我不确定我是否理解这个问题 - 你是在谈论属性,或者你想在Spring bean中加载一个XML文件,并且只想在您的配置中定义*哪个*文件? –

回答

1

你可以通过改变参数类型的资源实现它。你可以从资源对象中获取文件句柄

public class Bean { 
    private File file 
    public void setFile(Resource resource) { 
     this.file = resource.getFile() 
    } 
    //.... 
} 

并且在配置文件中可以像这样设置它。您可以使用classpath:如果该文件是类路径中jar的一部分。如果是外面则需要使用文件:?是否有使用Spring接受XML提供一个PropertyPlaceholderConfigurer类类]

<bean id="bean" class="blabla.Bean"> 
    <property name="file" value="file:path to file"/> 
</bean> 
0

PropertyPlaceholderConfigurer已通过支持xml属性文件

属性的xml文件格式如下。更多细节documentation -

<?xml version="1.0" encoding="UTF-8"?> 
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> 
    <properties> 
     <entry key="key1">Value 1</entry> 
     <entry key="key2">Value 2</entry> 
    </properties> 

可以使用

<context:property-placeholder 
    location="classpath:/com/myProject/spring_prop.xml" /> 
     <bean id="bean" class="org.MyBean"> 
     <property name="key1" value="${key1}" /> 
     </bean> 
+0

看到我的编辑,我解释一下 – maks

0

您的配置文件更改为以下,

<bean id="bean" class="blabla.Bean"> 
    <property name="file" ref="file"/> 
</bean> 

<bean id="file" class="java.io.File"> 
    <constructor-arg type="string"><value>C:\myfile.xml</value></constructor-arg> 
</bean>