技术

bean手动实例化依赖注入

This post is currently available in Chinese only. The original text follows.Open the Chinese page →

Spring bean 注入失败

现象

spring 的 component 在使用的时候,依赖注入全部都是 null,分析现象是没有进行注入

代码

使用class.newInstance() 获取bean的实例

拿到后的实例中,bean 中的依赖是没有注入进去的,导致使用的时候都是 nul 的

排查

spring scope

spring 的 bean 的管理模式,默认是单例模式 singleton

解决

public class xxximpl implements xxxManager, ApplicationContextAware {

    @Resource
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

		public void testBean(Class class){
	            Object object =  class.newInstance();
                autowireCapableBeanFactory.autowireBean(object);

		}

}

还是正常的新建实例,在创建实例之后,使用 autowireCapableBeanFactory 对新的 bean 进行相关依赖的注入