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

com.coditory.quark.context.BeanInitializer Maven / Gradle / Ivy

There is a newer version: 0.1.22
Show newest version
package com.coditory.quark.context;

import com.coditory.quark.context.annotations.Init;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

import static com.coditory.quark.context.DependencyResolver.resolveArguments;
import static com.coditory.quark.context.MethodBasedBeanCreator.simplifyMethodName;

final class BeanInitializer {
    private static final Logger log = LoggerFactory.getLogger(BeanInitializer.class);

    private BeanInitializer() {
        throw new UnsupportedOperationException("Do not instantiate utility class");
    }

    static void initializeBean(Object bean, BeanDescriptor descriptor, ResolutionContext context) {
        if (bean instanceof Initializable) {
            initializeBean((Initializable) bean, descriptor);
        }
        for (Method method : bean.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(Init.class)) {
                method.setAccessible(true);
                initializeBean(bean, descriptor, method, context);
            }
        }
    }

    private static void initializeBean(Object bean, BeanDescriptor descriptor, Method method, ResolutionContext context) {
        Timer timer = Timer.start();
        try {
            Object[] args = resolveArguments(method, context);
            method.invoke(bean, args);
        } catch (Exception e) {
            throw new BeanInitializationException("Could not initialize bean: " + descriptor.toShortString() + " using method: " + simplifyMethodName(method), e);
        }
        log.debug("Initialized bean {} using method {} in {}", descriptor.toShortString(), simplifyMethodName(method), timer.measureAndFormat());
        if (timer.isOverThreshold()) {
            log.warn("Detected long bean initialization. Bean: {}, Method: {}, Time: {}", descriptor.toShortString(), simplifyMethodName(method), timer.measureAndFormat());
        }
    }

    private static void initializeBean(Initializable bean, BeanDescriptor descriptor) {
        Timer timer = Timer.start();
        try {
            bean.init();
        } catch (Exception e) {
            throw new BeanInitializationException("Could not initialize bean: " + descriptor.toShortString(), e);
        }
        log.debug("Initialized bean {} in {}", descriptor.toShortString(), timer.measureAndFormat());
        if (timer.isOverThreshold()) {
            log.warn("Detected long bean initialization. Bean: {}, Time: {}", descriptor.toShortString(), timer.measureAndFormat());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy