常见错误使用方式

  1. 变成静态的在静态方法里直接使用:如图
    错误用法
    错误:直接会为空,借用一段网上不错的解释:针对static静态成员,我们有一些最基本的常识:静态变量(成员)它是属于类的,而非属于实例对象的属性;同样的静态方法也是属于类的,普通方法(实例方法)才属于对象。而Spring容器管理的都是实例对象,包括它的@Autowired依赖注入的均是容器内的对象实例,所以对于static成员是不能直接使用@Autowired注入的。

  2. 工具类里面没有@Component,这个就不做解释了。

正确用法

使用注解PostConstruct,
@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,为此,可以使用@PostConstruct注解一个方法来完成初始化
@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
执行优先级高于非静态的初始化块,它会在类初始化(类加载的初始化阶段)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员。

下面是正确的示例代码

import cn.hutool.http.HttpStatus;
import com.cmhit.common.core.domain.R;
import com.cmhit.system.api.RemoteLabelService;
import com.cmhit.system.api.vo.SysLabelApiVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class LabelsUtil {

    @Autowired
    private  RemoteLabelService labelService;

    public static  LabelsUtil labelsUtil;

    @PostConstruct
    public void init(){
        labelsUtil = this;
        labelsUtil.labelService=this.labelService;
    }
    public static Object getLabels(Long sourceId){
     try {
         R r = labelsUtil.labelService.getLabelList(sourceId);
         if (HttpStatus.HTTP_OK != r.getCode()){
             return null;
         }
        //你的逻辑代码,公司代码不能泄露
     }catch (Exception e){
         e.printStackTrace();
     }
     return null;
    }
}

使用
工具类方法使用

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐