【问题标题】:How to read a property in the an XML properties file in Spring Boot如何在 Spring Boot 中读取 XML 属性文件中的属性
【发布时间】:2018-09-28 21:45:15
【问题描述】:

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

<?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") 到Application 类,但我想读取 DAO 类中的资源文件,而不是 Application 类。

我该如何解决这个问题?

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    您可以使用您在配置中读取的信息在您的配置类中创建一个@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;
    
    }
    

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

    【讨论】:

    • 那么我必须创建一个新的配置文件还是使用 Application 类?
    • 创建一个新的配置类。你不需要在 Application 类上这样做
    • 好的,谢谢,用.properties文件代替xml文件怎么样,因为我不需要创建配置文件,我只需使用@PropertySource注释在 DAO 类上,然后 @Value("${sample.select}") private String mySqlFromXml;
    • 要使用 PropertySource,you need 在配置类中使用它。
    猜你喜欢
    • 2016-04-29
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2020-04-27
    • 2017-06-04
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多