【问题标题】:Spring Boot - configurable beansSpring Boot - 可配置的 bean
【发布时间】:2018-06-08 14:48:03
【问题描述】:

如何从外部 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 并且所有测试都通过?

我需要在外部配置 Target bean。

【问题讨论】:

  • 试试@ImportResource({"classpath*:config/config.xml"})。这个配置文件夹在哪里?在资源下?
  • @pvpkiran config文件夹是spring boot的config文件夹,application.properties所在。使用“类路径”,文件系统上的文件不会被加载,也不会覆盖 JAR 中的文件 ...

标签: spring spring-boot


【解决方案1】:

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

我的主类中有一个 @Configuration 类,带有 @Profile("default")@ImportResource("file:/config/beans.xml"),另一个 @Configuration 类在我的测试类中带有 @Profile("!default")@ImportResource("classpath*:test-beans.xml")

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-22
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多