在软件开发中,配置注入是一种常见的实践,它允许我们将应用程序的配置参数从代码中抽离出来,以便更灵活地进行配置更改。下面是几种常见的配置注入方式,以及相应的代码示例:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
private Properties properties;
public ConfigReader(String configFile) {
properties = new Properties();
try {
properties.load(new FileInputStream(configFile));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return properties.getProperty(key);
}
}
使用示例:
ConfigReader configReader = new ConfigReader("config.properties");
String username = configReader.getProperty("username");
String password = configReader.getProperty("password");
public class ConfigReader {
private String username;
private String password;
public ConfigReader() {
username = System.getenv("USERNAME");
password = System.getenv("PASSWORD");
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
使用示例:
ConfigReader configReader = new ConfigReader();
String username = configReader.getUsername();
String password = configReader.getPassword();
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class ConfigReader {
private String username;
private String password;
public ConfigReader(String configFile) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Config config = objectMapper.readValue(new File(configFile), Config.class);
username = config.getUsername();
password = config.getPassword();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
class Config {
private String username;
private String password;
// getters and setters
}
使用示例:
ConfigReader configReader = new ConfigReader("config.json");
String username = configReader.getUsername();
String password = configReader.getPassword();
这些是几种常见的配置注入方式,它们各有优劣,根据具体的需求和项目特点选择合适的方式进行配置注入。