- 报错代码:(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已导入):
springboot项目使用@Autowired 自动注入报错为null的解决
最新推荐文章于 2024-06-01 11:51:24 发布
关键词由CSDN通过智能技术生成