gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:41:39 24 4
gpt4 key购买 nike

我有一个抽象的 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 是一个非静态方法,无法在静态 block 内实例化。

如何从文件中初始化该变量的值?并且最好只进行一次。有没有标准方法可以做到这一点?像 @Value 这样的东西,而不是手动从 IO 读取?

最佳答案

希望对您有帮助。首次初始化后静态最终变量无法更改。

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);
}
}

关于java - 使用存储在外部文件中的值初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52886902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com