用存储在外部文件中的值初始化变量

时间:2018-10-19 06:28:03

标签: java

我有一个Email类,它是抽象的。它有几个子级:AuthenticationEmailMarketingEmail等。我想用存储在外部文件中的字符串初始化字段的值(为最终静态值)。

起初我虽然可以使用Spring的@Value,但事实证明该类必须是一个组件。然后,我尝试了以下代码(静态初始化等):

public abstract class UserAccountAuthenticationEmail extends Email implements Serializable {    
    @Value("${email.address.from.authentication}")
    private final static String SENDER_EMAIL_ADDRESS;

    static {

        Properties prop = new Properties();
        String propFileName = "config.properties";
        InputStream inputStream;
        if (inputStream != null) {
            prop.load(inputStream);
            inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
    }

    @Override
    public String getSender() {
        return SENDER_EMAIL_ADDRESS;
    }
}

它也不起作用,因为getClass是一种非静态方法,无法在静态块中实例化。

如何从文件初始化此变量的值?最好只有一次。有什么标准方法可以做到吗?类似于@Value,而不是从IO手动读取?

2 个答案:

答案 0 :(得分:1)

希望它可以为您提供帮助。第一次初始化后不能更改静态最终变量。

public  class UserAccountAuthenticationEmail  implements Serializable {

private final static String SENDER_EMAIL_ADDRESS =getVal();
public static String getVal() {

    try {
        Properties prop = new Properties();
        String propFileName = "C:\\SMS\\config.properties";
        InputStream inputStream;
        inputStream = new FileInputStream(propFileName);
        if (inputStream != null) {
            prop.load(inputStream);
           return prop.getProperty("email");
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return "";
}

public static void main(String[] args) {
    System.out.println(SENDER_EMAIL_ADDRESS);
  }
}

答案 1 :(得分:0)

以这种方式解决:

private final static String DEFAULT_SENDER_EMAIL_ADDRESS;

static {
    String value = "";
    try {
        Properties prop = new Properties();
        String propFileName = "application.properties";
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(propFileName);
        if (inputStream != null) {
            prop.load(inputStream);
           value = prop.getProperty("email.authentication.sender");
        }

    }
    catch (Exception e){
        e.printStackTrace();
    }
    DEFAULT_SENDER_EMAIL_ADDRESS = value;
}

public String getSender() {
    return DEFAULT_SENDER_EMAIL_ADDRESS;
}