001/*
002 * Copyright 2002-2017 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.io.Serializable;
020import java.lang.reflect.Method;
021
022import org.aopalliance.intercept.MethodInterceptor;
023import org.aopalliance.intercept.MethodInvocation;
024
025import org.springframework.lang.Nullable;
026
027/**
028 * AOP Alliance MethodInterceptor for declarative cache
029 * management using the common Spring caching infrastructure
030 * ({@link org.springframework.cache.Cache}).
031 *
032 * <p>Derives from the {@link CacheAspectSupport} class which
033 * contains the integration with Spring's underlying caching API.
034 * CacheInterceptor simply calls the relevant superclass methods
035 * in the correct order.
036 *
037 * <p>CacheInterceptors are thread-safe.
038 *
039 * @author Costin Leau
040 * @author Juergen Hoeller
041 * @since 3.1
042 */
043@SuppressWarnings("serial")
044public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable {
045
046        @Override
047        @Nullable
048        public Object invoke(final MethodInvocation invocation) throws Throwable {
049                Method method = invocation.getMethod();
050
051                CacheOperationInvoker aopAllianceInvoker = () -> {
052                        try {
053                                return invocation.proceed();
054                        }
055                        catch (Throwable ex) {
056                                throw new CacheOperationInvoker.ThrowableWrapper(ex);
057                        }
058                };
059
060                try {
061                        return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments());
062                }
063                catch (CacheOperationInvoker.ThrowableWrapper th) {
064                        throw th.getOriginal();
065                }
066        }
067
068}