首页 > 解决方案 > Spring Boot - 可配置的 bean

问题描述

如何从外部 XML 文件加载我的 spring bean?

示例 xml:

<bean class="com.mycompany.Config">
    <property name="targets">
        <list>
            <bean class="com.mycompany.Target">
                <property name="url">http://bla</property>
                <property name="authentication">
                    <bean class="com.mycompany.Auth">
                        <property name="type" value="basic"/>
                        <property name="user" value="user1"/>
                        <property name="pass" value="asdf"/>
                    </bean>
                </property>
            </bean>
            <bean class="com.mycompany.Target">
                <property name="url">http://otherbla</property>
                <property name="authentication">
                    <bean class="com.mycompany.Auth">
                        <property name="type" value="basic"/>
                        <property name="user" value="user2"/>
                        <property name="pass" value="start123"/>
                    </bean>
                </property>
            </bean>
            [as many Target beans as I want]
        </list>
    </property>
</bean>

弹簧靴:

@SpringBootApplication(scanBasePackages = {"com.mycompany"})
@ImportResource({"file:config/config.xml"})
public class Application {

    /**
     * Spring Boot Startpoint.
     *
     * @param args Commandline arguments
     */
    public static void main(final String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
    }
}

我尝试了不同的方法,但都没有奏效。如果我在我的 jar 中包含 xml,我不知道如何在 jar 外部覆盖它。否则测试无法启动上下文。我应该如何设置@ImportResource({"file:config/config.xml"})以便应用程序可以找到 xml 并且所有测试都通过?

我需要从外部配置目标 bean。

标签: springspring-boot

解决方案


由于我还没有找到答案,我想出了以下想法:

@Configuration我的主要课程中的一个类使用@Profile("default")and@ImportResource("file:/config/beans.xml")@Configuration我的测试类中的另一类使用@Profile("!default")and @ImportResource("classpath*:test-beans.xml")

完整的 POC 见https://gitlab.com/Sheldor5/configurable-spring-boot-sample


推荐阅读