【发布时间】:2021-11-06 17:08:03
【问题描述】:
在启动时,我正在根据 A 类中的数据库类型创建一个字符串。然后我想在调用 setBitAndSqlExpression() 函数后将该字符串值注入到 B 类中。注入后,我想在 B 类中使用该变量。如果用户在运行时初始化后发出请求,则执行 B 类。
请注意,它们位于不同的包中。我无法通过构造函数传递它们。
class A { //code first enters here
public String BITAND_SQL_EXPRESSION;
public void setBitAndSqlExpression() {
try {
String driverName = dataSource.getConnection().getMetaData().getDriverName();
if (driverName.contains("PostgreSQL")) {
BITAND_SQL_EXPRESSION = "%s" + "::INTEGER" + " & %s = %s";
} else {
BITAND_SQL_EXPRESSION = "BITAND (%s,%s) = %s";
}
} catch (Exception e) {
LOGGER.warn("Driver cannot be found. Setting operations will not work correctly.");
}
}
}
class B { //enters here if only user makes a request after class A creation.
public String BITAND_SQL_EXPRESSION; // want to use the value at class A
public B(
...//codes and constructors.
}
【问题讨论】:
-
从您的代码类 A 和 B 中,Spring 管理的 bean 不正确吗?为什么不能通过构造函数将结果从
A#setBitAndSqlExpression传递给 B?请向我们展示您如何在代码中使用这两个类 -
我无法通过构造函数传递它们 - 创建 setter 和 getter
-
A 类有 Annotation 基础弹簧配置,B 类没有。基本上我很困惑如何从 B 到达 A。
-
编辑您的问题并发布您的代码请不要描述而是发布代码。
标签: java spring spring-boot dependency-injection