All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.logging.log4j.plugins.di.Binding Maven / Gradle / Ivy

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.logging.log4j.plugins.di;

import java.util.function.Supplier;

import org.apache.logging.log4j.util.Lazy;

/**
 * Bindings combine a {@link Key} with a factory {@link Supplier} to get instances of the key's type.
 *
 * @param  type of key to bind instance factory
 */
public final class Binding implements Supplier {
    private final Key key;
    private final Supplier factory;

    private Binding(final Key key, final Supplier factory) {
        this.key = key;
        this.factory = factory;
    }

    public Key getKey() {
        return key;
    }

    @Override
    public T get() {
        return factory.get();
    }

    public static  DSL from(final Key key) {
        return new DSL<>(key);
    }

    public static  DSL from(final Class type) {
        return new DSL<>(Key.forClass(type));
    }

    public static final class DSL {
        private final Key key;

        private DSL(final Key key) {
            this.key = key;
        }

        public Binding to(final Supplier factory) {
            return new Binding<>(key, factory);
        }

        public Binding toSingleton(final Supplier factory) {
            return new Binding<>(key, Lazy.lazy(factory));
        }

        public Binding toInstance(final T instance) {
            return new Binding<>(key, Lazy.value(instance));
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy