spring - 从 xml 配置中读取 spring yml 属性

标签 spring spring-boot

我正在尝试从 spring-bean.xml 中的 application.yml 读取属性,如下所示:

<bean name="#{bean.name}" />

是否可以 ?或者我应该指定我的 application.yml 文件的位置?

最佳答案

是的,这是可能的

For YAML Properties


  • 您必须使用 YamlPropertiesFactoryBean
    <bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
        <property name="resources" value="classpath:application.yml"/>
    </bean>
    
    <context:property-placeholder properties-ref="yamlProperties"/>
    
  • 然后在 src/main/resource/application.yaml 中定义您的属性
    bean:
       name: foo
    
  • 现在使用可以使用xml中的属性来创建bean
    <bean name="${bean.name}"
    class="net.asifhossain.springmvcxml.web.FooBar"/>
    

  • 这是我完整的 XML 配置
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
            <property name="resources" value="classpath:application.yaml"/>
        </bean>
    
        <context:property-placeholder properties-ref="yamlProperties"/>
    
        <bean name="${bean.name}" class="net.asifhossain.springmvcxml.web.FooBar"/>
    </beans>
    

    关于spring - 从 xml 配置中读取 spring yml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46094792/

    相关文章:

    java - 如何在 Thymeleaf HTML 上使用 Java get 函数?

    java builder模式对象的spring bean创建

    java - Spring Boot 中的 Maven 依赖问题

    java - Spring 启动: Cannot access page html on localhost (404)

    java - Spring Tool Suite 4中的内容自动完成

    java - 如何定义 POJO 来保存提交表单中的数据列表?

    java - Spring异常处理程序,无法访问请求属性

    java - 添加 AOP 建议时 Spring Boot 应用程序上下文被破坏

    java - 如何告诉 Spring Boot 哪个主类用于可执行 jar?

    java - maven 版本 :prepare for Spring Boot 2. 3.1.RELEASE 的问题