解決方案:
1. 如果你的項目由多個模塊且為分布式部署, 則可考慮使用設置System.property
2. 一般只是極少數的代碼出現此情況, 那么建議直接在你的單例Service初始化時, 在靜態塊中直接改變TypeUtils的變量值, 如果用Spring的話可以使用InitializingBean進行處理
TypeUtils.compatibleWithJavaBean = true;
3. 此變量是public的注意要在一個地方進行改動, 避免線程安全問題
項目組使用FastJson, 在輸出下面一段Json的時候出現此問題, 期望是大寫但是fastJson將值自動首字母變成小寫了
{"code":0,"message":"","result":{"facts":{"ip":{"aCUN_ONE_MIN":0,"aCUN_TEN_MIN":0}},"level":0}}
查詢后發現fastjson內部做Bean轉換時會使用到 com.alibaba.fastjson.util.TypeUtils, 核心代碼如下, 在類加載的時候會去讀取環境變量 fastjson.compatibleWithJavaBean, 找不到則使用默認值false,將會導致首字母小寫
public static boolean compatibleWithJavaBean = false; static { try { String prop = System.getProperty("fastjson.compatibleWithJavaBean"); if ("true".equals(prop)) { compatibleWithJavaBean = true; } else if ("false".equals(prop)) { compatibleWithJavaBean = false; } } catch (Throwable ex) { // skip } }
public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap, boolean sorted) {
String propertyName;
if (Character.isUpperCase(c3)) {
if (compatibleWithJavaBean) {
propertyName = Introspector.decapitalize(methodName.substring(3));
} else {
propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
}
} else if (c3 == '_') {
propertyName = methodName.substring(4);
} else if (c3 == 'f') {
propertyName = methodName.substring(3);
} else {
continue;
}}