1. 程式人生 > >spring 根據beanName獲取bean物件,呼叫其方法

spring 根據beanName獲取bean物件,呼叫其方法

通用類

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 實現ApplicationContextAware介面的回撥方法,設定上下文環境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 獲得spring上下文
     * @return ApplicationContext spring上下文
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     * 獲取bean
     * @param name service註解方式name為小駝峰格式
     * @return  Object bean的例項物件
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
}

程式碼呼叫

//反射方式執行
                Object object = SpringContextUtil.getBean(beanName);

                Method method = ReflectionUtils.findMethod(object.getClass(), methodName, argsClass);

                Object o = ReflectionUtils.invokeMethod(method, object, args);

jsp獲取bean

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

    AreaCodSynServiceImpl s = (AreaCodSynServiceImpl) context.getBean("areaCodSynServiceImpl");