在一个自定义的工具类中用到了service层的方法,直接通过@Autowired注解来进行注入的时候出了NullPointerException
初始化静态资源需要用到@PostConstruct注解
举个栗子
@Component
public class GetCodeUtil {
@Autowired
private UserService userService;
private static GetCodeUtils getCodeUtils;
@PostConstruct
public void init() {
getCodeUtils = this;
getCodeUtils.userService=this.userService;
}
//静态方法
public static String getUserCode() {
String code = RandomStringUtils.randomAlphanumeric(8);
if (null == getCodeUtils.userService.selectByCode(code)
) {
return code;
} else return getUserCode();
}
}
一开始以为很简单的写个@Autowired写个@Component就好了,测试的时候发现自己天真了,记录一下此次经验,并希望可以帮到更多人