从 xml 配置中读取 spring yml 属性

san*_*nny 4 spring spring-boot

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

<bean name="#{bean.name}" />
Run Code Online (Sandbox Code Playgroud)

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

mir*_*sif 6

Yes It's Possible

For YAML Properties

  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"/>
    
    Run Code Online (Sandbox Code Playgroud)
  2. Then define your property in src/main/resource/application.yaml

    bean:
       name: foo
    
    Run Code Online (Sandbox Code Playgroud)
  3. Now use can use the property in xml to create a bean

    <bean name="${bean.name}"
    class="net.asifhossain.springmvcxml.web.FooBar"/>
    
    Run Code Online (Sandbox Code Playgroud)

Here's my complete XML config

<?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>
Run Code Online (Sandbox Code Playgroud)