Spring 普通java类 使用 @Autowired 注入 为null 问题解决方法

问题: 有时我们会在普通类里或工具类里注入service或mapper,那么我们直接使用@Autowired注入,注入的service或mapper在方法里是不能直接使用,会报null。再一个,如果是工具类,工具类里一般都是静态方法,更是无法使用。

解决方法:

第一步:在java类上添加@Component注解,将java类实例到spring容器中。

import org.springframework.stereotype.Component;

@Component
public class Test {

    
}

第二步:使用@Autowired注入service或mapper。

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;


@Component
public class Test {

    // 需要注入的 service
    @Autowired
    private IJsjbSjjkLogService logService;


}

第三步:使用@PostConstruct注解初始化java类和service或mapper。

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class Test {

    // 需要注入的 service
    @Autowired
    private IJsjbSjjkLogService logService;

    // 当前类
    private static Test test;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        test = this;
        test.logService = this.logService;
    }


}

第四步:以上三步完成后,在方法里就可以使用注入的service或mapper了。

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class Test {

    // 需要注入的 service
    @Autowired
    private IJsjbSjjkLogService logService;

    // 当前类
    private static Test test;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        test = this;
        test.logService = this.logService;
    }

    /**
     * 需要使用 serive 的方法
     */
    public static void test(){
        // 调用查询方法
        JsjbSjjkLog log = test.logService.selectJsjbSjjkLogById(1L);
    }

}

你可能感兴趣的:(java,spring)