在AWS Cloud Development Kit(AWS-CDK)中,当尝试从包含交叉引用的堆栈中创建实用程序类时,可能会遇到“无法从堆栈中使用交叉引用”的错误。
解决此问题的一种方法是使用静态方法而不是实例方法。在以下示例中,我们创建了一个名为“Utility”的实用程序类,该类包含静态方法“addPrefix”,该方法采用两个字符串参数并在它们之间添加前缀。这个实用程序类是从另一个堆栈(“my-stack”)使用的,因此我们必须将它以模块的形式导出。
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
export class Utility {
static addPrefix(prefix: string, str: string): string {
return prefix + str;
}
}
export class MyStack extends cdk.Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
const utility = new Utility();
const prefixed = utility.addPrefix('foo', 'bar');
}
}
通过修改代码以使用静态方法,我们避免了从堆栈中使用交叉引用的问题。现在,我们可以使用“Utility.addPrefix”而不是“utility.addPrefix”来调用实用程序类中的方法,如以下示例所示:
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Utility } from './utility';
export class MyStack extends cdk.Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
const prefixed = Utility.addPrefix('foo', 'bar');
}
}