Reputation: 7719
I have an Email
class which is abstract. It has several children: AuthenticationEmail
, MarketingEmail
, etc. I want to initialize value of a field (which is final static) with a string stored in an external file.
At first I though I could use Spring's @Value
but it turned out that the class needs to be a component. Then I tried the following code (static initialization and etc.):
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;
}
}
It doesn't work either, as getClass
is a non-static method and cannot be instantiated inside the static block.
How can I initialize the value of this variable from a file? and preferably only one time. Is there any standard method to do that? something like @Value
, instead of manually reading from IO?
Upvotes: 0
Views: 434
Reputation: 7719
Fixed it this way:
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;
}
Upvotes: 0
Reputation: 11
Hope it can help you. A static final variable can't be changed after the first initialization.
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);
}
}
Upvotes: 1