【问题标题】:How to Inject a runtime created string to another class using Spring如何使用 Spring 将运行时创建的字符串注入另一个类
【发布时间】: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


【解决方案1】:

你可以使用工厂方法吗? 它将在 B 类的包中:

public interface IB {
    methodA();
    methodB();
}
class B implements IB{ //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.
}
public final class BFactory {
    public static IB create(String sqlExpression) {
        return new B(sqlExpression);
    }
}

那么在A类的包中你就可以调用这个工厂了

BFactory.create(BITAND_SQL_EXPRESSION);

A 将取决于接口而不是 B 实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2013-11-24
    • 1970-01-01
    • 2015-02-11
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多