springboot项目使用@Autowired 自动注入报错为null的解决
·
- 报错代码:(tempservice看做一个普通的类即可)
@Autowired public tempservice ts; - 解决:
- 以上代码修改为(前提,tempservice已导入):
public tempservice ts = GetBeanUtil.getBean(tempservice.class); - 并增加代码:(导入要使用的工具类,根据自己放置下方工具类的位置来写)
import com.nk.wsy.config.GetBeanUtil; - 增加修改代码中的GetBeanUtil工具类:
package com.nk.wsy.config; //此处包名记得根据实际修改 import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class GetBeanUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (GetBeanUtil.applicationContext == null) { GetBeanUtil.applicationContext = applicationContext; } } /** * 返回ApplicationContext * * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 返回bean * * @param beanName beanName * @return bean */ public static Object getBean(String beanName) { return applicationContext.getBean(beanName); } /** * 获取bean * * @param c c * @param <T> 泛型 * @return bean */ public static <T> T getBean(Class<T> c) { return applicationContext.getBean(c); } /** * 获取bean * @param c c * @param name 名称 * @param <T> 泛型 * @return T 泛型 */ public static <T> T getBean(String name, Class<T> c) { return getApplicationContext().getBean(name, c); } } -
再运行看看,应该就可以成功了。
- 以上代码修改为(前提,tempservice已导入):
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)