特别提醒:一定要注意文件结构
WebappApplication 一定要在包的最外层,否则Spring无法对所有的类进行托管,会造成@Autowired 无法注入。
1. 添加工具类获取在 Spring 中托管的 Bean
(1)工具类
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); } }
(2)使用
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 无法注入问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!