通過Spring上下文獲取Bean、Service等類


         引子:(springboot項目)自己在開發中遇到的坑,如果程序不是從前端發送請求,直接使用xxxxService層的API,這時Serivce層會有注入為NULL的情況(加入了@Autowired注解),無法獲取Service(博主暫時不知道原因,可能和底層有關,有知道原因的大牛歡迎留言解答,感謝!)。

  下面說一下通過Spring上下文獲取Service解決方案:

  第一步:首先創建一個springUtils工具類(叫什么自己起就行),下面就是代碼直接復制粘貼到自己的項目(注意:引入的jar包也寫出來了,有使用的小伙伴不要引錯jar包)。

 

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {


private static ApplicationContext applicationContext = null;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtils.applicationContext == null){
SpringUtils.applicationContext = applicationContext;
}
}

//獲取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);
}



}
第二步:在調用service的方法中創建applicationContext,通過getBean(自己項目中的Service的類.class)
ApplicationContext applicationContext = SpringUtils.getApplicationContext();
            
xxxService xxxservice = applicationContext.getBean(xxxService.class);
舉例:之后就可以使用里邊的方法xxxservice.save();




  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM