Java 如何在Spring Boot中读取XML属性文件中的属性

Java 如何在Spring Boot中读取XML属性文件中的属性,java,spring-boot,Java,Spring Boot,我创建了一个包含sql查询的XML属性文件,如下所示: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="sample.select"> <![CDATA[ The SQL que

我创建了一个包含sql查询的XML属性文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="sample.select">
        <![CDATA[
            The SQL query goes here
        ]]>
    </entry>    
</properties>

在我的DAO中,我想获得属性“sample.select”,但我不知道在Spring Boot中是如何实现的,当我搜索它时,我发现我必须将注释
@ImportResource(“classpath:my file.xml”)
添加到应用程序类中,但我想读取DAO类中的ressource文件,而不是应用程序类


如何解决这个问题?

您可以使用在配置类中读取的信息在配置类中创建一个
@Bean
。之后,您可以在DAO类中注入Bean

例如:

@ImportResource("classpath:my-file.xml")
@Configuration
public class SampleSelectConfig {

    private @Value("#{sample.select}") String select;

    @Bean
    String mySqlFromXml() {
        return select;
    }
}
在DAO中,您可以注入Bean:

@Component
class YourDAO {

    @Autowired
    private String mySqlFromXml;

}

我无法测试上面的代码,但想法是一样的。

那么我必须创建一个新的配置文件还是使用应用程序类?创建一个新的配置类。您不需要在应用程序类上这样做好了,谢谢,使用
.properties
文件而不是xml文件怎么样,因为我不需要创建配置文件,我只需要在DAO类上使用
@PropertySource
注释,然后使用
@Value(${sample.select}”)私有字符串mySqlFromXml
使用PropertySource,在配置类中使用它。