从XML配置文件中读取Spring YML属性

5
我正在尝试在spring-bean.xml中读取application.yml的属性,方法如下:

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

这是可能的吗?还是我应该指定我的application.yml文件的位置?

1
你已经在使用Spring Boot了,它会加载这些文件。请使用${bean.name}而不是#{bean.name},后者是一个SpEL表达式。 - M. Deinum
@M.Deinum - 请问您能在这里指导一下吗:https://dev59.com/AHoPtIcB2Jgan1znvTAs? - PAA
1个回答

7

是的,这是可能的

对于YAML属性

  1. You have to use 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"/>
    
  2. Then define your property in src/main/resource/application.yaml

    bean:
       name: foo
    
  3. Now use can use the property in xml to create a bean

    <bean name="${bean.name}"
    class="net.asifhossain.springmvcxml.web.FooBar"/>
    
这是我完整的XML配置:

这里是我的完整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>

谢谢你的回答,但是我想从YAML文件中读取值,而不是从*.properties文件中读取。 - sanny
我们如何从yaml文件中读取多个属性? - PAA
请问有人可以在这里提供指导吗:https://dev59.com/AHoPtIcB2Jgan1znvTAs? - PAA
我们如何从Application.properties中读取作为Map? - Jeff Cook

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接