对象无法注册到Spring容器中,手动从spring容器中拿到我们需要的对象
当前对象没有注册到spring容器中,此时无法new object() 的方式创建对象,否则所有@Autowired 注入的对象都为null;
处理方式:
手动创建一个类@Component注册到Spring容器 并实现ApplicationContextAware 接口,实现对象方法,完成获取spring容器的通道,再通过通道获取我们所需要的对象,此对象里面关联注入的其他对象都正常,可以正常使用了
/** * 用于手动获取spring无法注册的对象 */ @Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } System.out.println("---------------------------------------------------------------------"); System.out.println("---------------------------------------------------------------------"); System.out.println("---------------me.shijunjie.util.SpringUtil------------------------------------------------------"); System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.applicationContext+"========"); System.out.println("---------------------------------------------------------------------"); } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } }
没有注册到Spring容器的对象,调用此通道即可获取spring容器的对象:
获取WordDictionariesEntityService对象
wordDictionariesEntityService = (WordDictionariesEntityService) SpringUtil.getBean(WordDictionariesEntityService.class);