001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.cache.interceptor;
018
019import java.lang.reflect.Method;
020import java.lang.reflect.Modifier;
021import java.util.Collection;
022import java.util.Collections;
023import java.util.Map;
024import java.util.concurrent.ConcurrentHashMap;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028
029import org.springframework.core.BridgeMethodResolver;
030import org.springframework.core.MethodClassKey;
031import org.springframework.util.ClassUtils;
032
033/**
034 * Abstract implementation of {@link CacheOperation} that caches attributes
035 * for methods and implements a fallback policy: 1. specific target method;
036 * 2. target class; 3. declaring method; 4. declaring class/interface.
037 *
038 * <p>Defaults to using the target class's caching attribute if none is
039 * associated with the target method. Any caching attribute associated with
040 * the target method completely overrides a class caching attribute.
041 * If none found on the target class, the interface that the invoked method
042 * has been called through (in case of a JDK proxy) will be checked.
043 *
044 * <p>This implementation caches attributes by method after they are first
045 * used. If it is ever desirable to allow dynamic changing of cacheable
046 * attributes (which is very unlikely), caching could be made configurable.
047 *
048 * @author Costin Leau
049 * @author Juergen Hoeller
050 * @since 3.1
051 */
052public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource {
053
054        /**
055         * Canonical value held in cache to indicate no caching attribute was
056         * found for this method and we don't need to look again.
057         */
058        private static final Collection<CacheOperation> NULL_CACHING_ATTRIBUTE = Collections.emptyList();
059
060
061        /**
062         * Logger available to subclasses.
063         * <p>As this base class is not marked Serializable, the logger will be recreated
064         * after serialization - provided that the concrete subclass is Serializable.
065         */
066        protected final Log logger = LogFactory.getLog(getClass());
067
068        /**
069         * Cache of CacheOperations, keyed by method on a specific target class.
070         * <p>As this base class is not marked Serializable, the cache will be recreated
071         * after serialization - provided that the concrete subclass is Serializable.
072         */
073        private final Map<Object, Collection<CacheOperation>> attributeCache =
074                        new ConcurrentHashMap<Object, Collection<CacheOperation>>(1024);
075
076
077        /**
078         * Determine the caching attribute for this method invocation.
079         * <p>Defaults to the class's caching attribute if no method attribute is found.
080         * @param method the method for the current invocation (never {@code null})
081         * @param targetClass the target class for this invocation (may be {@code null})
082         * @return {@link CacheOperation} for this method, or {@code null} if the method
083         * is not cacheable
084         */
085        @Override
086        public Collection<CacheOperation> getCacheOperations(Method method, Class<?> targetClass) {
087                if (method.getDeclaringClass() == Object.class) {
088                        return null;
089                }
090
091                Object cacheKey = getCacheKey(method, targetClass);
092                Collection<CacheOperation> cached = this.attributeCache.get(cacheKey);
093
094                if (cached != null) {
095                        return (cached != NULL_CACHING_ATTRIBUTE ? cached : null);
096                }
097                else {
098                        Collection<CacheOperation> cacheOps = computeCacheOperations(method, targetClass);
099                        if (cacheOps != null) {
100                                if (logger.isDebugEnabled()) {
101                                        logger.debug("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheOps);
102                                }
103                                this.attributeCache.put(cacheKey, cacheOps);
104                        }
105                        else {
106                                this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE);
107                        }
108                        return cacheOps;
109                }
110        }
111
112        /**
113         * Determine a cache key for the given method and target class.
114         * <p>Must not produce same key for overloaded methods.
115         * Must produce same key for different instances of the same method.
116         * @param method the method (never {@code null})
117         * @param targetClass the target class (may be {@code null})
118         * @return the cache key (never {@code null})
119         */
120        protected Object getCacheKey(Method method, Class<?> targetClass) {
121                return new MethodClassKey(method, targetClass);
122        }
123
124        private Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
125                // Don't allow no-public methods as required.
126                if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
127                        return null;
128                }
129
130                // The method may be on an interface, but we need attributes from the target class.
131                // If the target class is null, the method will be unchanged.
132                Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
133                // If we are dealing with method with generic parameters, find the original method.
134                specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
135
136                // First try is the method in the target class.
137                Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
138                if (opDef != null) {
139                        return opDef;
140                }
141
142                // Second try is the caching operation on the target class.
143                opDef = findCacheOperations(specificMethod.getDeclaringClass());
144                if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
145                        return opDef;
146                }
147
148                if (specificMethod != method) {
149                        // Fallback is to look at the original method.
150                        opDef = findCacheOperations(method);
151                        if (opDef != null) {
152                                return opDef;
153                        }
154                        // Last fallback is the class of the original method.
155                        opDef = findCacheOperations(method.getDeclaringClass());
156                        if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
157                                return opDef;
158                        }
159                }
160
161                return null;
162        }
163
164
165        /**
166         * Subclasses need to implement this to return the caching attribute for the
167         * given class, if any.
168         * @param clazz the class to retrieve the attribute for
169         * @return all caching attribute associated with this class, or {@code null} if none
170         */
171        protected abstract Collection<CacheOperation> findCacheOperations(Class<?> clazz);
172
173        /**
174         * Subclasses need to implement this to return the caching attribute for the
175         * given method, if any.
176         * @param method the method to retrieve the attribute for
177         * @return all caching attribute associated with this method, or {@code null} if none
178         */
179        protected abstract Collection<CacheOperation> findCacheOperations(Method method);
180
181        /**
182         * Should only public methods be allowed to have caching semantics?
183         * <p>The default implementation returns {@code false}.
184         */
185        protected boolean allowPublicMethodsOnly() {
186                return false;
187        }
188
189}