net.bubble.common.utils.BeanContextUtil.java Source code

Java tutorial

Introduction

Here is the source code for net.bubble.common.utils.BeanContextUtil.java

Source

/**
 * Copyright [2015-2017] [https://github.com/bubble-light/]
 *
 * 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 net.bubble.common.utils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.bubble.common.exception.CommonException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * SpringBean?
 * @author shiwen_xiao<xiaosw@msn.cn>
 * @since 2015128
 */
public class BeanContextUtil implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(BeanContextUtil.class);

    private ConfigurableApplicationContext applicationContext = null;

    /* (non-Javadoc)
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    /**
     * Spring?
     * @param beanName ??(beanId)
     * @return Object 
     */
    public Object getBean(String beanName) {
        return getBean(beanName, null);
    }

    /**
     * Spring?(?)
     * @param beanName ??(beanId)
     * @param args ?
     * @return Object 
     */
    public Object getBean(String beanName, Object... args) {
        logger.info("BeanName is:{}", beanName);
        return this.applicationContext.getBean(beanName, args);
    }

    /**
     * Spring?(?)
     * @param beanClass class
     * @return Object 
     */
    public Object getBean(Class<?> beanClass) {
        return getBean(beanClass, null);
    }

    /**
     * Spring?(?)
     * @param beanClass class
     * @param args ?
     * @return Object 
     */
    public Object getBean(Class<?> beanClass, Object... args) {
        logger.info("BeanName is:{}", beanClass.getName());
        return this.applicationContext.getBean(beanClass, args);
    }

    /**
     * ?Spring?</br>
     * ???war/ear???????
     * @param configurationLocations spring?
     * @throws CommonException Common?
     */
    public void loadCustomizedConfiguration(List<String> configurationLocations) throws CommonException {
        logger.info("Loading custom configuration file ......");
        if (configurationLocations == null || configurationLocations.size() < 1) {
            logger.info("No custom configuration file !");
            return;
        }
        try {
            XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(
                    (BeanDefinitionRegistry) applicationContext.getBeanFactory());
            beanDefinitionReader.setResourceLoader(applicationContext);
            beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(applicationContext));
            for (String localtion : configurationLocations)
                beanDefinitionReader.loadBeanDefinitions(applicationContext.getResources(localtion));
        } catch (BeansException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Load custom bean definitions has error !", e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Read configuration file has error !", e);
        }
        logger.info("Load Custom configuration file is finish !");
    }

    /**
     * Spring??</br>
     * ?
     * @param clz class
     * @return Map<String,Object> Map
     * @throws CommonException 
     */
    public Map<String, Object> getBeanMapWithAnnotation(Class<? extends Annotation> clz) throws CommonException {
        try {
            Map<String, Object> objMap = new HashMap<String, Object>();
            Map<String, Object> proxyMap = this.applicationContext.getBeansWithAnnotation(clz);
            for (Iterator<String> iterator = proxyMap.keySet().iterator(); iterator.hasNext();) {
                String key = iterator.next();
                Object obj = getTargetObject(proxyMap.get(key));
                objMap.put(key, obj);
            }
            return objMap;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Get object map with annotation has error!");
        }

    }

    /**
     * ?
     * @param proxy ?
     * @return Object 
     * @throws CommonException ??
     */
    public Object getTargetObject(Object proxy) throws CommonException {
        try {
            if (!AopUtils.isAopProxy(proxy)) {// ??
                return proxy;
            }
            if (AopUtils.isCglibProxy(proxy)) {// cglib?
                return getCglibProxyTargetObject(proxy);
            }
            if (AopUtils.isJdkDynamicProxy(proxy)) {// jdk??
                return getJdkDynamicProxyTargetObject(proxy);
            }
            //null
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Get target Object has error!");
        }
    }

    /**
     * ?cglib?</br>
     * Spring??AOP?cglib??
     * @param proxy ?
     * @return Object 
     * @throws CommonException cblib???
     */
    public Object getCglibProxyTargetObject(Object proxy) throws CommonException {
        try {
            Field field = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
            field.setAccessible(true);
            Object dynamicAdvisedInterceptor = field.get(proxy);
            Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
            advised.setAccessible(true);
            return ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
        } catch (SecurityException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("The method of object with cglib can't be read !", e);
        } catch (NoSuchFieldException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Can't find field in cglib object !", e);
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Inject parameter to cglib object has error !", e);
        } catch (IllegalAccessException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Access cglib object has error !", e);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Get cglib target object has error !", e);
        }
    }

    /**
     * ?JDK??</br>
     * Spring??AOP?JDK??
     * @param proxy ?
     * @return Object 
     * @throws CommonException jdk???
     */
    public Object getJdkDynamicProxyTargetObject(Object proxy) throws CommonException {
        try {
            Field field = proxy.getClass().getSuperclass().getDeclaredField("h");
            field.setAccessible(true);
            AopProxy aopProxy = (AopProxy) field.get(proxy);
            Field advised = aopProxy.getClass().getDeclaredField("advised");
            advised.setAccessible(true);
            Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
            return target;
        } catch (SecurityException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("The method of object with Dynamic jdk proxy can't be read !", e);
        } catch (NoSuchFieldException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Can't find field in Dynamic jdk proxy object !", e);
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Inject parameter to Dynamic jdk proxy object has error !", e);
        } catch (IllegalAccessException e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Access Dynamic jdk proxy object has error !", e);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new CommonException("Get Dynamic jdk proxy target object has error !", e);
        }

    }
}