spring - 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。
解决方案
由于我还没有找到答案,我想出了以下想法:
@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
推荐阅读
- python - 如何在同一虚拟环境中将私人使用的包与与项目相关的包分开?
- prolog - Prolog,动态规划,斐波那契数列
- ansible - 仅使用 selectattr 的条件 set_fact?
- java - 哪个注释仅用于接受数字作为输入?
- flutter - StreamBuilder 监听流和普通监听方法的区别
- javascript - setInterval 和 setState 中的 useEffect 错误
- php - SQLSTATE [23000]:违反完整性约束:1048 列 'cne' 不能为空
- c# - C#使用OleDbConnection将数据插入excel,但数据在错误的行上
- swift - 在 Swift 中以正确的方式从 URLSession 解码原始数据
- php - php(客户端套接字) java(服务器套接字)无法接收第二个数据