1 /* 2 * Copyright 2002-2011 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package org.springframework.cache.interceptor; 18 19 import java.lang.reflect.Method; 20 21 import org.springframework.cache.interceptor.KeyGenerator; 22 23 /** 24 * Default key generator. Returns {@value #NO_PARAM_KEY} if no 25 * parameters are provided, the parameter itself if only one is given or 26 * a hash code computed from all given parameters' hash code values. 27 * Uses the constant value {@value #NULL_PARAM_KEY} for any 28 * {@code null} parameters given. 29 * 30 * @author Costin Leau 31 * @author Chris Beams 32 * @since 3.1 33 */ 34 public class DefaultKeyGenerator implements KeyGenerator { 35 36 public static final int NO_PARAM_KEY = 0; 37 public static final int NULL_PARAM_KEY = 53; 38 generate(Object target, Method method, Object... params)39 public Object generate(Object target, Method method, Object... params) { 40 if (params.length == 1) { 41 return (params[0] == null ? NULL_PARAM_KEY : params[0]); 42 } 43 if (params.length == 0) { 44 return NO_PARAM_KEY; 45 } 46 int hashCode = 17; 47 for (Object object : params) { 48 hashCode = 31 * hashCode + (object == null ? NULL_PARAM_KEY : object.hashCode()); 49 } 50 return Integer.valueOf(hashCode); 51 } 52 53 } 54