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;
}

猜你喜欢

转载自my.oschina.net/u/1404252/blog/769751