static {
Properties prop = new Properties();
InputStream in = null;
try {
in = new ClassPathResource("application.properties").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
prop.load(in);
clientid = prop.getProperty("clientid").trim();
HOST = prop.getProperty("mqtt.host").trim();
userName = prop.getProperty("mqtt.userName").trim();
passWord = prop.getProperty("mqtt.passWord").trim();
} catch (IOException e) {
logger.info("读取配置文件异常:{}", e.getMessage());
}
logger.info("clientid:{}", clientid);
init(clientid);
start();
}
由于spring中静态代码块的执行顺序在@Value之前,所以在静态代码块中用@Value取不到值
而这样取,打包放到linux服务器又找不到路径,上面的取法本地,linux都可以找到
static {
Properties prop = new Properties();
InputStream in = Object.class.getResourceAsStream("/application.properties");
try {
prop.load(in);
url = prop.getProperty("url").trim();
logger.info("url:{}",url);
} catch (IOException e) {
e.printStackTrace();
}
}