mybatis 源碼中的細節
1、mybatis 中大量使用final 修飾對象
/**
* mybatis 最重要的一個配置 保存着mybatis的關鍵配置信息
*/
private final Configuration configuration;
因爲 final 修飾的對象的內存地址是不可變的,也就是說向下傳遞,任何一個地方改了了對象裏面的值,其他的放的對象的值也就會被變更,有點類型Java中volitale 但是final 的優點更多,final修復的對象訪問速度會更快
2、Map的computeIfAbsent方法 獲取和添加
computeIfAbsent是jdk1.8的新特性
源碼的位置在org.apache.ibatis.binding.MapperProxy
/**
* 緩存Mapper的method
* @param method
* @return
*/
private MapperMethod cachedMapperMethod(Method method) {
return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
下面是對這一塊代碼的詳解
static final Map<String, Object> map = new HashMap<String, Object>();
public static String handel(String key) {
return key += "xxxxx";
}
public static void main(String[] args) {
String value = getMapValue("key");
}
//computeIfAbsent 替換的核心代碼 有則返回 沒有則創建並塞入map
public static Object getMapValue(String key) {
Object value = map.get(key);
if (value == null) {
value =handel(key);
map.put(key, value);
}
return value;
}
上面這麼負責的代碼如果替換的話可以用下面簡單的代碼來替換
static final Map<String, Object> map = new HashMap<String, Object>();
public static String handel(String key) {
return key += "xxxxx";
}
public static void main(String[] args) {
String key = "key";
map.computeIfAbsent(key,k->handel(key));
}
效果是一摸一樣的
computeIfAbsent 方法主要是用來替換取值的問題有則返回沒有則創建並壓入map
3、Collecitons.unmodifiableList 返回一個不可變更的list
代碼在org.apache.ibatis.mapping.MappedStatement
//生成一個不可變的結果集mappedStatement.resultMaps = Collections.unmodifiableList(mappedStatement.resultMaps);
樣例代碼
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e"));
list = Collections.unmodifiableList(list);
list.add("h");
System.out.println(list);
}
執行後
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at com.test.map.MapTest.main(MapTest.java:14)
我們發現生成的list不能進行其他操作了,這樣避免生成的list隨意被添加刪除,注意的是原來的list,如果沒有被覆蓋是可以進行操作的,會把操作結果同步到鎖定的list中
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e"));
List<String> list1 = Collections.unmodifiableList(list);
list.add("h");
System.out.println(list1);
}
返回結果
[a, b, c, d, e, h]