问题描述
背景:假设我正在将代码从旧代码迁移到 Spring Boot 2 应用程序。 旧代码有自己的 IoC 机制,我想在新的 Spring 应用程序中重用旧库,而无需修改库代码库。
库代码仅使用字段注入。它使用类似于 @Value
的注解来注入一些属性,比如 @InjectString
。此外,每个字段顶部也有 @Inject
注释。所以我想使用的所有库都或多或少是这样的:
package com.mylibrary;
public class LibraryA {
@Inject
@InjectString("db.properties.poolEnabled")
private String poolEnabled;
...
假设:
-
db.properties.poolEnabled
等所有属性都已存在于System.getProperties()
中。 -
LibraryA
类已经在 Spring IoC 控制之下,只是缺少必需的字段 bean:
No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject(),@com.mylibrary.InjectString(name="db.properties.poolEnabled")}
问题:
如何重用旧代码并让 Spring 知道根据 @Inject
名称(可以从 @InjectString
检索?
System.getProperty
的字段中
我在考虑 3 个可能的解决方案:
-
在bean构建过程中,让Spring知道当它在寻找一个String类型的Bean并且该字段有
@InjectString
注解时,它可以从System.getProperty()
中获取一个值作为bean值. -
在类扫描期间,使用
@InjectString
获取所有字段并以某种方式在那里附加一个@Value
注释,也许 Spring 会知道在那里插入什么 -
扫描所有用
@InjectString
注释的字段,为所有字段创建名为 bean 的 String 并将@Resource(name="...")
附加到每个字段 bean 声明
哪个想法听起来最好,哪些 Spring 类将有助于实现?
到目前为止,我可能更喜欢解决方案 1),因为它听起来像是一个单一的 Spring 类覆盖。 在解决方案 2) 和 3) 中,我缺少可以在 IoC 构建期间覆盖以动态提供额外 bean 定义的 Spring 类 - 您知道我可以使用什么吗?
感谢您的任何提示!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)