001/*
002 * Copyright 2013 Atteo.
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 *      http://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 */
016package org.atteo.moonshine.springdata;
017
018import javax.inject.Inject;
019
020import org.atteo.moonshine.jta.Transaction;
021import org.springframework.data.repository.core.support.RepositoryFactorySupport;
022
023import com.google.inject.Provider;
024
025/**
026 * Provides repository of given class.
027 *
028 * <p>
029 * Requires {@link RepositoryFactorySupport}.
030 * </p>
031 */
032public class RepositoryProvider<T> implements Provider<T> {
033    @Inject
034    private RepositoryFactorySupport factory;
035
036    private Class<T> klass;
037
038    public RepositoryProvider(Class<T> klass) {
039        this.klass = klass;
040    }
041
042    @Override
043    public T get() {
044        return Transaction.require(new Transaction.ReturningRunnable<T, RuntimeException>() {
045            @Override
046            public T run() throws RuntimeException {
047                return factory.getRepository(klass);
048            }
049        });
050    }
051
052}