构造代码块
什么是构造代码块
只听过静态代码块,是在程序运行的过程中,加载到类 的数据里
构造代码块
运行在构造方法前面执行,如果没有构造方法,但是被Componet修饰的话,就再bean生成之前先执行
看样例
@Component
@Slf4j
public class PrepareNode implements Node<UmpAlarmModel> {
private Map<String,String> metricMapping;
{
metricMapping = Maps.newConcurrentMap();
metricMapping.put("tp50","method.tp50");
metricMapping.put("tp90","method.tp90");
metricMapping.put("tp99","method.tp99");
metricMapping.put("tp999","method.tp999");
metricMapping.put("availableRate","method.availrate");
metricMapping.put("invokeCount","method.count.total");
metricMapping.put("max","method.max");
metricMapping.put("avg","method.avg");
metricMapping.put("min","method.min");
}
}
静态代码块
静态代码块的执行顺序是和定义的顺序依赖的,写到后面就后面执行。一般和静态变量放在一起使用,用于静态变量之后
private static final SafeConcurrentHashMap<SlowLogType, SearchRequestBuilder> builders = new SafeConcurrentHashMap<>();
static {
builders.computeIfAbsent(SlowLogType.REDIS_MASTER_LATENCY,(k) -> redisSlowLogSearchRequestBuilder);
builders.computeIfAbsent(SlowLogType.REDIS_PROXY_LATENCY,(k) -> redisSlowLogSearchRequestBuilder);
builders.computeIfAbsent(SlowLogType.ES_QUERY,(k) -> esSlowLogSearchRequestBuilder);
builders.computeIfAbsent(SlowLogType.ES_INDEX,(k) -> esSlowLogSearchRequestBuilder);
};
放到了静态变量builders之后执行
原创:做时间的朋友