解决反射调用方法时获取bean失败的问题
作者:关老头
文章描述了通过反射机制调用类方法时遇到的@Autowired注入失败和事务回滚失败的问题,原因是反射生成的对象未被SpringIOC容器管理,解决方案是通过applicationContext.getBean("className")方法获取Spring管理的bean来解决注入和事务问题
1、问题描述
通过反射机制调用某个类的方法时,此类内@Autowired注入失败,并且事务回滚失败。
2、原因
Class.forName(“className”).newInstance()
实例化对象后与Spring IOC容器无关(自己通过反射获取的对象,没有交给spring容器管理),所以@Autowired无法关联注入对象也无法支持事务。
3、解决方案
通过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); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。