The class injected in static is Null null pointer exception

Recently, when injecting in the Static static method, a null pointer exception is reported, and the error is shown in the following figure:
insert image description here

Read the explanation of an article:
https://blog.csdn.net/weixin_35676504/article/details/114097611?utm_source=app&app_version=5.3.1&utm_source=app

The code has been modified, using annotations and set methods to inject, as shown in the figure below:
insert image description here

In summary, there are three solutions:

1. Add @Autowire to the constructor

@Component
public class JwtUtils {
    
    

	@Resource
	static
    private RedisService redisService;

	@Autowired
    public JwtUtils(RedisService redisService) {
    
    
        JwtUtils.redisService = redisService;
    }
}

2. Use Set injection

@Component
public class JwtUtils {
    
    

	static
    private RedisService redisService;

	@Autowired
    public void setRedisService(RedisService redisService) {
    
    
        JwtUtils.redisService = redisService;
    }

3. Annotate with @PostConstruct

@Component
public class JwtUtils {
    
    

	static
    private RedisService staticRedisService;
    
	private RedisService redisService;

	/**
	* 注释用于在完成依赖注入以后执行任何初始化之后需要执行的方法。必须在类投入使用之前调用此方法。
	*/
	@PostConstruct
    public void beforeInit() {
    
    
		staticRedisService = redisService;
	}
}

4. Pass the value directly (quote mapper as an example)

@Component
public class JwtUtils {
    
    
//不用注入、不用赋值等方式,直接传值

	 public static String handleDesensitizationMobile(MemberMapper memberMapper,String mobile) {
    
    
        MemberMapper member = memberMapper;
        String result = member.selectById(memberShiroVO.getId()).getAccount();
        return result;
    }
}

Guess you like

Origin blog.csdn.net/Ivy_Xinxxx/article/details/124681351