一. 静态代码块
-
为什么要用静态代码块?
一般情况下,如果有些代码必须在项目启动的时候就执行的时候,需要使用静态代码块,这些代码是自己主动执行的。看下面这个例子,这是一个jdis连接池,首先我必须先加载配置文件才能继续其他工作,为保证加载配置首先执行,而且静态代码块有一个作用就是随着类的加载而执行,而且只执行一次,我只需要在开始加载配置,而不需要每次操作时都加载配置
public class JedisPoolUtils {
private static JedisPool jedisPool;
static {
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建properties对象
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(properties.getProperty