com.github.steveash.spring.WiringFactorySupport.java Source code

Java tutorial

Introduction

Here is the source code for com.github.steveash.spring.WiringFactorySupport.java

Source

/*
 * Licensed 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 com.github.steveash.spring;

import static com.github.steveash.spring.WiringFactoryBeanFactoryPostProcessor.getPrototypeBeanNameFromFactory;

import javax.annotation.CheckReturnValue;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.google.common.base.Preconditions;

/**
 * Support class that allows a prototype instance that you supply to be registered in the container and
 * injected with @Resource, have @PostConstruct, etc. called.
 *
 * Create a spring-managed factory and then before returning your constructed instance call the wire() method
 * below, passing the instance, to have it injected with resources and registered in the container.
 *
 * @author Steve Ash
 * @See com.argodata.match.util.spring.WiringFactoryBeanFactoryPostProcessor
 */
public abstract class WiringFactorySupport<T> implements WiringFactory<T>, ApplicationContextAware {

    private AutowireCapableBeanFactory ctx;
    private String beanName;

    @SuppressWarnings("unchecked")
    @CheckReturnValue
    protected T wire(T instance) {
        Preconditions.checkNotNull(beanName,
                "classes that extend WiringFactorySupport must be a bean in the container");

        return (T) ctx.configureBean(instance, beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext.getAutowireCapableBeanFactory();
        this.beanName = getPrototypeBeanNameFromFactory(getClass());
    }
}