IDEA Spring-boot 使用@Component注解的工具类,用@Autowired注入 @Service或者@Repository 会空指针(使用@PostContruct )

使用idea编译器时,对于spring-boot的项目,大都使用注解,那么:

一、现象:@Component标注的Util类,用@Autowired自动导入 @Service和@Repository会报空指针

二、原因:网上查阅的文章说,无法持久化引用

三、解决方法:

         1、增加一个静态变量:  private static ClassNameUtil.java zKK;

         2、使用注解@PostContruct ,让该util在启动spring时,执行初始化方法(这样util才存在,才可以注入其他)

         3、调用方式:工具类名.引用类名.方法名(zKK.devicesRe.methd())

         4、例子:

@Component
public class ZKAndKafkaManageUtil implements IServiceControlCommonOperation{

    @Autowired
	DevicesRepository devicesRe;

    private static ZKAndKafkaManageUtil zKK;  //1、加个静态变量

	@PostConstruct   //2、加个注解并初始化
	public void init (){
		zKK=this;
	}

        //3、引用,特别注意:引用方式为: 工具类名.引用类名.方法名(zKK.devicesRe.methd())
        public void test2(){
    	    zKK.devicesRe.findDeviceByIpv4Addr("222.143.1.193"); 
	}

注解拓展:

1、@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法

2、spring中Constructor、@Autowired、@PostConstruct的顺序

其实从依赖注入的字面意思就可以知道,要将对象p注入到对象a,那么首先就必须得生成对象p与对象a,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowired注解,那么@Autowired注入是发生在A的构造方法执行完之后的。

如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

Constructor(构造) >> @Autowired(注入) >> @PostConstruct(调用)

public Class AAA {
    @Autowired
    private BBB b;
     
    public AAA() {
        System.out.println("此时b还未被注入: b = " + b);
    }
  
    @PostConstruct
    private void init() {
        System.out.println("@PostConstruct将在依赖注入完成后被自动调用: b = " + b);
    }
}

参考网址:

https://blog.csdn.net/weixin_42911069/article/details/88849789

https://www.cnblogs.com/kelelipeng/p/11309591.html

https://www.cnblogs.com/zxf330301/p/9265718.html

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