SpringBoot 注入的@service为空,运行时报空指针

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);

SpringBoot 注入的@service为空,运行时报空指针

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18529

发表评论