001/*
002 * Copyright 2002-2019 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;
021import java.util.ArrayList;
022import java.util.Collection;
023
024import org.springframework.util.Assert;
025
026/**
027 * Composite {@link CacheOperationSource} implementation that iterates
028 * over a given array of {@code CacheOperationSource} instances.
029 *
030 * @author Costin Leau
031 * @author Juergen Hoeller
032 * @since 3.1
033 */
034@SuppressWarnings("serial")
035public class CompositeCacheOperationSource implements CacheOperationSource, Serializable {
036
037        private final CacheOperationSource[] cacheOperationSources;
038
039
040        /**
041         * Create a new CompositeCacheOperationSource for the given sources.
042         * @param cacheOperationSources the CacheOperationSource instances to combine
043         */
044        public CompositeCacheOperationSource(CacheOperationSource... cacheOperationSources) {
045                Assert.notEmpty(cacheOperationSources, "CacheOperationSource array must not be empty");
046                this.cacheOperationSources = cacheOperationSources;
047        }
048
049        /**
050         * Return the {@code CacheOperationSource} instances that this
051         * {@code CompositeCacheOperationSource} combines.
052         */
053        public final CacheOperationSource[] getCacheOperationSources() {
054                return this.cacheOperationSources;
055        }
056
057
058        @Override
059        public Collection<CacheOperation> getCacheOperations(Method method, Class<?> targetClass) {
060                Collection<CacheOperation> ops = null;
061                for (CacheOperationSource source : this.cacheOperationSources) {
062                        Collection<CacheOperation> cacheOperations = source.getCacheOperations(method, targetClass);
063                        if (cacheOperations != null) {
064                                if (ops == null) {
065                                        ops = new ArrayList<CacheOperation>();
066                                }
067                                ops.addAll(cacheOperations);
068                        }
069                }
070                return ops;
071        }
072
073}