如何使用 Spring 将运行时创建的字符串注入另一个 class

How to Inject a runtime created string to another class using Spring

在启动时,我根据 class A 中的数据库类型创建一个字符串。然后我想在调用 setBitAndSqlExpression() 函数后将该字符串值注入到 class B .注入后,我想在 Class B 中使用该变量。如果用户在 运行 时间初始化后发出请求,则执行 Class 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.
}

你可以使用工厂方法吗? 它将在 B class :

的包中
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);
    }
}

然后在classA的包中你可以调用这个工厂

BFactory.create(BITAND_SQL_EXPRESSION);

A 将依赖于接口而不是 B 实现。