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.aop.support.AopUtils;
030import org.springframework.core.MethodClassKey;
031import org.springframework.lang.Nullable;
032import org.springframework.util.ClassUtils;
033
034/**
035 * Abstract implementation of {@link CacheOperation} that caches attributes
036 * for methods and implements a fallback policy: 1. specific target method;
037 * 2. target class; 3. declaring method; 4. declaring class/interface.
038 *
039 * <p>Defaults to using the target class's caching attribute if none is
040 * associated with the target method. Any caching attribute associated with
041 * the target method completely overrides a class caching attribute.
042 * If none found on the target class, the interface that the invoked method
043 * has been called through (in case of a JDK proxy) will be checked.
044 *
045 * <p>This implementation caches attributes by method after they are first
046 * used. If it is ever desirable to allow dynamic changing of cacheable
047 * attributes (which is very unlikely), caching could be made configurable.
048 *
049 * @author Costin Leau
050 * @author Juergen Hoeller
051 * @since 3.1
052 */
053public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource {
054
055        /**
056         * Canonical value held in cache to indicate no caching attribute was
057         * found for this method and we don't need to look again.
058         */
059        private static final Collection<CacheOperation> NULL_CACHING_ATTRIBUTE = Collections.emptyList();
060
061
062        /**
063         * Logger available to subclasses.
064         * <p>As this base class is not marked Serializable, the logger will be recreated
065         * after serialization - provided that the concrete subclass is Serializable.
066         */
067        protected final Log logger = LogFactory.getLog(getClass());
068
069        /**
070         * Cache of CacheOperations, keyed by method on a specific target class.
071         * <p>As this base class is not marked Serializable, the cache will be recreated
072         * after serialization - provided that the concrete subclass is Serializable.
073         */
074        private final Map<Object, Collection<CacheOperation>> attributeCache = new ConcurrentHashMap<>(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        @Nullable
087        public Collection<CacheOperation> getCacheOperations(Method method, @Nullable Class<?> targetClass) {
088                if (method.getDeclaringClass() == Object.class) {
089                        return null;
090                }
091
092                Object cacheKey = getCacheKey(method, targetClass);
093                Collection<CacheOperation> cached = this.attributeCache.get(cacheKey);
094
095                if (cached != null) {
096                        return (cached != NULL_CACHING_ATTRIBUTE ? cached : null);
097                }
098                else {
099                        Collection<CacheOperation> cacheOps = computeCacheOperations(method, targetClass);
100                        if (cacheOps != null) {
101                                if (logger.isTraceEnabled()) {
102                                        logger.trace("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheOps);
103                                }
104                                this.attributeCache.put(cacheKey, cacheOps);
105                        }
106                        else {
107                                this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE);
108                        }
109                        return cacheOps;
110                }
111        }
112
113        /**
114         * Determine a cache key for the given method and target class.
115         * <p>Must not produce same key for overloaded methods.
116         * Must produce same key for different instances of the same method.
117         * @param method the method (never {@code null})
118         * @param targetClass the target class (may be {@code null})
119         * @return the cache key (never {@code null})
120         */
121        protected Object getCacheKey(Method method, @Nullable Class<?> targetClass) {
122                return new MethodClassKey(method, targetClass);
123        }
124
125        @Nullable
126        private Collection<CacheOperation> computeCacheOperations(Method method, @Nullable Class<?> targetClass) {
127                // Don't allow no-public methods as required.
128                if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
129                        return null;
130                }
131
132                // The method may be on an interface, but we need attributes from the target class.
133                // If the target class is null, the method will be unchanged.
134                Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
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        @Nullable
172        protected abstract Collection<CacheOperation> findCacheOperations(Class<?> clazz);
173
174        /**
175         * Subclasses need to implement this to return the caching attribute for the
176         * given method, if any.
177         * @param method the method to retrieve the attribute for
178         * @return all caching attribute associated with this method, or {@code null} if none
179         */
180        @Nullable
181        protected abstract Collection<CacheOperation> findCacheOperations(Method method);
182
183        /**
184         * Should only public methods be allowed to have caching semantics?
185         * <p>The default implementation returns {@code false}.
186         */
187        protected boolean allowPublicMethodsOnly() {
188                return false;
189        }
190
191}