
SpringBoot 注入的@service为空,运行时报空指针
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
@Component
public class ServerHandler extends IoHandlerAdapter {
@Autowired
protected HealthDataService healthDataService;
private static ServerHandler serverHandler ;
@PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
public void init() {
serverHandler = this;
serverHandler.healthDataService = this.healthDataService;
// 初使化时将已静态化的testService实例化
}
//测试调用
public void test(){
serverHandler .healthDataService.<你的service层方法>;
}1.创建一个SpringUtil工具类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public final class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
System.out.println("=============================================="+
"========ApplicationContext配置成功,在普通类可以通过调用ToolSpring.getAppContext()获取applicationContext对象,applicationContext="
+ applicationContext + "==========");
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过类名称获取Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
}2.在启动类上面添加注解
@Import(SpringUtil.class)
依赖 import org.springframework.context.annotation.Import;3.在普通类中使用SpringUtil创建service类
TestService testService = (TestService )SpringUtil.getBean(TestService.class); testService.save(testEntity);
Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/javajgs.com/wp-content/plugins/wechat-social-login/templates/share/share-bar.php on line 7