com.art4ul.loadinstead.bean.LoadInsteadBeanFactoryPostProcessor.java Source code

Java tutorial

Introduction

Here is the source code for com.art4ul.loadinstead.bean.LoadInsteadBeanFactoryPostProcessor.java

Source

/*
 * Copyright (C) 2014 Artsem Semianenka (http://art4ul.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 com.art4ul.loadinstead.bean;

import com.art4ul.loadinstead.exception.LoadClassMapperException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.io.IOException;
import java.util.List;

public class LoadInsteadBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private List<String> loadInstedPacks;

    public LoadInsteadBeanFactoryPostProcessor(List<String> loadInstedPacks) {
        this.loadInstedPacks = loadInstedPacks;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ClassMapper mapper;
        try {
            mapper = ClassMapper.load(loadInstedPacks);
        } catch (IOException e) {
            throw new LoadClassMapperException("Exception in process of loading classes to replace", e);
        }
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            Class<?> beanClass = beanFactory.getType(beanName);
            Class<?> classToReplace = mapper.getClassToReplace(beanClass);
            if (classToReplace != null) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                if (beanDefinition != null) {
                    beanDefinition.setBeanClassName(classToReplace.getName());
                }

            }
        }
    }

}