当前位置: 移动技术网 > IT编程>开发语言>Java > java 反射调用方法时获取bean失败解决方案

java 反射调用方法时获取bean失败解决方案

2020年07月31日  | 移动技术网IT编程  | 我要评论
反射调用方法时获取bean失败Service service = (Service)Class.forName("com.service.TestService").newInstance();// 加载类,并实例化对象Method objMethod = service.getClass().getDeclaredMethod("test");//获取方法objMethod.invoke(service);//执行方法通过反射机制调用TestServiceImpl实现类的test方法时,Test

反射调用方法时获取bean失败

Service service = (Service)Class.forName("com.service.TestService").newInstance();// 加载类,并实例化对象
Method objMethod = service.getClass().getDeclaredMethod("test");//获取方法
objMethod.invoke(service);//执行方法

通过反射机制调用TestServiceImpl实现类的test方法时,TestServiceImpl类内@Autowired注入失败,并且事务回滚失败。
原因:Class.forName(“className”).newInstance()实例化对象后与Spring IOC容器无关,所以@Autowired无法关联注入对象也无法支持事务。

解决方案

通过applicationContext.getBean(“className”)来获取bean。

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext; // Spring应用上下文环境

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringContextUtil.applicationContext == null){
            SpringContextUtil.applicationContext  = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static Object getBean(String name, Class requiredType)
            throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    // 通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}
Service  service = (Service) SpringContextUtil.getBean(Class.forName("com.service.TestService"));
Method objMethod = service.getClass().getDeclaredMethod("test");//获取方法
objMethod.invoke(service);//执行方法

本文地址:https://blog.csdn.net/Marlene_me/article/details/107663050

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网