0
点赞
收藏
分享

微信扫一扫

spring 根据beanName获取bean对象,调用其方法

玉新行者 2022-04-25 阅读 59
java后端

通用类

@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");
举报

相关推荐

0 条评论