利用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