利用SpringBeanUtil 来获取 IOC 容器中的bean
有时候在代码中,不希望使用自动注入,而是手动获取Spring容器以及Spring容器中的某个对象
1、首先写一个class实现ApplicationContextAware#
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @Component public class SpringBeanUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringBeanUtil.applicationContext = applicationContext; } /** * 通过名称在spring容器中获取对象 * * @param beanName * @return */ public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } }
2、在代码调用SpringBeanUtil的getBean获取指定的bean对象了
https://www.cnblogs.com/houchen/p/14005211.html
您的资助是我最大的动力!
金额随意,欢迎来赏!