這篇文章給大家分享的是有關Springboot @Autowired無法注入怎么辦的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
特別提醒:一定要注意文件結構
WebappApplication 一定要在包的最外層,否則Spring無法對所有的類進行托管,會造成@Autowired 無法注入。
1. 添加工具類獲取在 Spring 中托管的 Bean
?。?)工具類
package com.common; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @program: IPC_1P * @description: 獲取在spring中托管的bean * @author: johnny * @create: 2018-08-03 16:24 **/ public class SpringContextUtil { private static ApplicationContext applicationContext; // Spring應用上下文 // 下面的這個方法上加了@Override注解,原因是繼承ApplicationContextAware接口是必須實現的方法 public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } public static Object getBean(String name, Class requiredType) throws BeansException { return applicationContext.getBean(name, requiredType); } public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return applicationContext.isSingleton(name); } public static Class getType(String name) throws NoSuchBeanDefinitionException { return applicationContext.getType(name); } public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { return applicationContext.getAliases(name); } }
?。?)使用
1)程序啟動時,實例化 SpringContextUtil
@SpringBootApplication public class WebappApplication { private static ApplicationContext applicationContext; public static void main(String[] args) { applicationContext = SpringApplication.run(WebappApplication.class, args); // SpringContextUtil springContextUtil = new SpringContextUtil(); springContextUtil.setApplicationContext(applicationContext); System.out.println("服務器啟動測試!"); }
2)在使用 @Service 的方法中,通過@Autowired 注入,使用SpringcontexUtil 獲取Bean上下文
@Autowired SenderService senderService; public class Package_State { @Autowired SenderService senderService; @Component private Package_State() { senderService = (SenderService)SpringContextUtil.getBean("senderService"); } }
感謝各位的閱讀!關于“Springboot @Autowired無法注入怎么辦”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。