aws-cdk 中属性文件的 FileNotFoundException

FileNotFoundException for properties file in aws-cdk

我一直在尝试读取属性文件并希望它是动态的,我在 aws-cdk 中这样做。

我的项目布局:

classxxxstage.java有如下代码:

public class xxxstage extends Stage {
    public xxxstage(final Construct scope, final String id) {
        this(scope, id, null);
    }
    public xxxstage(final Construct scope, final String id, final StageProps props) {
        super(scope, id, props);

        String account = null;
        InputStream inputStream = null;

        try {
            Properties prop = new Properties();
            String propFileName = "resources/config.properties";
            inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
            System.out.println("inputStream is -> "+inputStream);
 
            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }
 
            // get the property value and print it out
            account = prop.getProperty("account.id");
 
            System.out.println("account id -> "+account);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        } finally {
            try{
                inputStream.close();
            }
            catch (Exception e){
                System.out.println("Exception: " + e);
            }
        }

        new xxxStack(this, "xxxStack", StackProps.builder()
        .env(new Environment.Builder()
                .account(account)
                .region("us-east-1")
                .build())
        .build());
    }
}

我尝试打印 System.out.println("inputStream is -> "+inputStream); 的行显示为空,因此 FileNotFoundException.

值得注意的是,当我 运行 它在本地 java-project 上时它工作正常,但是它在 aws-codepipeline 的构建阶段失败了。 在管道构建阶段,我得到:

  • inputStream is -> null
  • Exception: java.io.FileNotFoundException: property file 'resources/config.properties' not found in the classpath
  • Exception: java.lang.NullPointerException

有人可以帮忙吗?

编辑 1 - 添加环境变量:

环境变量

我找到了答案 ,它对我有用。属性文件的位置很重要。