利用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对象了

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM