解决Springboot @Autowired 无法注入问题
特别提醒:一定要注意文件结构
WebappApplication一定要在包的最外层,否则Spring无法对所有的类进行托管,会造成@Autowired无法注入。
1.添加工具类获取在Spring中托管的Bean
(1)工具类
packagecom.common; importorg.springframework.beans.BeansException; importorg.springframework.beans.factory.NoSuchBeanDefinitionException; importorg.springframework.context.ApplicationContext; importorg.springframework.context.ApplicationContextAware; /** *@program:IPC_1P *@description:获取在spring中托管的bean *@author:johnny *@create:2018-08-0316:24 **/ publicclassSpringContextUtil{ privatestaticApplicationContextapplicationContext;//Spring应用上下文 //下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法 publicstaticvoidsetApplicationContext(ApplicationContextapplicationContext) throwsBeansException{ SpringContextUtil.applicationContext=applicationContext; } publicstaticApplicationContextgetApplicationContext(){ returnapplicationContext; } publicstaticObjectgetBean(Stringname)throwsBeansException{ returnapplicationContext.getBean(name); } publicstaticObjectgetBean(Stringname,ClassrequiredType) throwsBeansException{ returnapplicationContext.getBean(name,requiredType); } publicstaticbooleancontainsBean(Stringname){ returnapplicationContext.containsBean(name); } publicstaticbooleanisSingleton(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.isSingleton(name); } publicstaticClassgetType(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.getType(name); } publicstaticString[]getAliases(Stringname) throwsNoSuchBeanDefinitionException{ returnapplicationContext.getAliases(name); } }
(2)使用
1)程序启动时,实例化SpringContextUtil
@SpringBootApplication publicclassWebappApplication{ privatestaticApplicationContextapplicationContext; publicstaticvoidmain(String[]args){ applicationContext=SpringApplication.run(WebappApplication.class,args); // SpringContextUtilspringContextUtil=newSpringContextUtil(); springContextUtil.setApplicationContext(applicationContext); System.out.println("服务器启动测试!"); }
2)在使用@Service的方法中,通过@Autowired注入,使用SpringcontexUtil获取Bean上下文
@Autowired SenderServicesenderService; publicclassPackage_State{ @Autowired SenderServicesenderService; @Component privatePackage_State(){ senderService=(SenderService)SpringContextUtil.getBean("senderService"); } }
总结
以上所述是小编给大家介绍的解决Springboot@Autowired无法注入问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!