Spring中獲取bean

import java.lang.reflect.InvocationTargetException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.MethodInvoker;

@Service("springBeanUtils")
public class SpringBeanUtils implements ApplicationContextAware {
    private SpringBeanUtils() {
    }

    public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
        applicationContext = _applicationContext;
    }

    /**
     * 獲取Bean對象
     * 
     * [@param](https://my.oschina.net/u/2303379) name
     *            bean的配置名稱
     * [@return](https://my.oschina.net/u/556800) bean對象
     */
    public Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 獲取Bean對象
     * 
     * [@param](https://my.oschina.net/u/2303379) name
     *            bean的配置名稱
     * [@param](https://my.oschina.net/u/2303379) requiredType
     *            bean的類型
     * @return bean對象
     */
    public <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 獲取Bean對象
     * 
     * @param requiredType
     *            bean的類型
     * @return bean對象
     */
    public <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 運行Bean中指定名稱的方法並返回其返回值
     * 
     * @param beanName
     *            beanName對象
     * @param methodName
     *            方法名
     * @param arguments
     *            參數值
     * @return 運行bean中指定名稱的方法的返回值
     */
    public Object invokeBeanMethod(String beanName, String methodName, Object[] arguments) {
        try {
            // 初始化
            MethodInvoker methodInvoker = new MethodInvoker();
            methodInvoker.setTargetObject(getBean(beanName));
            methodInvoker.setTargetMethod(methodName);

            // 設置參數
            if (arguments != null && arguments.length > 0) {
                methodInvoker.setArguments(arguments);
            }

            // 準備方法
            methodInvoker.prepare();

            // 執行方法
            return methodInvoker.invoke();
        } catch (ClassNotFoundException e) {
            logger.error(" ClassNotFoundException ", e);
        } catch (NoSuchMethodException e) {
            logger.error(" NoSuchMethodException ", e);
        } catch (InvocationTargetException e) {
            logger.error(" InvocationTargetException ", e);
        } catch (IllegalAccessException e) {
            logger.error(" IllegalAccessException ", e);
        }

        return null;
    }

    private ApplicationContext applicationContext;
}
相關文章
相關標籤/搜索