jrouter.spring.SpringObjectFactory.java Source code

Java tutorial

Introduction

Here is the source code for jrouter.spring.SpringObjectFactory.java

Source

/*
 * Copyright (C) 2010-2111 sunjumper@163.com
 *
 * 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 jrouter.spring;

import jrouter.ObjectFactory;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 *  springframework 
 */
public class SpringObjectFactory implements ObjectFactory, ApplicationContextAware {

    /**
     * springframework AutowireCapableBeanFactory
     */
    protected AutowireCapableBeanFactory autowireCapableBeanFactory;

    /**
     * springframework {@code byName}
     */
    private int autowireMode = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;

    /**
     * 
     */
    public SpringObjectFactory() {
    }

    /**
     * ApplicationContext
     *
     * @param applicationContext ApplicationContext
     */
    public SpringObjectFactory(ApplicationContext applicationContext) {
        setApplicationContext(applicationContext);
    }

    @Override
    public <T> T newInstance(Class<T> clazz) {
        if (AutowireCapableBeanFactory.AUTOWIRE_NO == autowireMode)
            return autowireCapableBeanFactory.createBean(clazz);
        return (T) autowireCapableBeanFactory.createBean(clazz, autowireMode, false);
    }

    @Override
    public final void setApplicationContext(ApplicationContext applicationContext) {
        autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    /**
     * 
     *
     * @return 
     */
    public int getAutowireMode() {
        return autowireMode;
    }

    /**
     * 
     *
     * @param autowireMode 
     *
     * @see AutowireCapableBeanFactory#AUTOWIRE_BY_NAME
     * @see AutowireCapableBeanFactory#AUTOWIRE_BY_TYPE
     * @see AutowireCapableBeanFactory#AUTOWIRE_CONSTRUCTOR
     * @see AutowireCapableBeanFactory#AUTOWIRE_NO
     */
    public void setAutowireMode(int autowireMode) {
        this.autowireMode = autowireMode;
    }

    @Override
    public Class<?> getClass(Object obj) {
        return AopProxyUtils.ultimateTargetClass(obj);
    }
}