spring无法自动注入静态变量、spring注入null 的解决方法;

方式一:使用@Resource注解set方法,将注入的bean对象赋值给静态变量。

/**
 * @description: 自定義公共方法
 * @author: H2103424
 * @createTime: 2021/1/22 下午 02:15
 **/
@Component
public class CustomUtil {

    private static UserService userService;
    private static MailSendService mailSendService;

    @Resource
    public void setMailSendService(MailSendService mailSendService) {
        CustomUtil.mailSendService = mailSendService;
    }

    @Resource
    public void setUserService(UserService userService) {
        CustomUtil.userService = userService;
    }

    /**
     * @description: 根據 用戶編號list 獲取用戶郵箱list
     * @author:  H2103424
     * @dateTime: 2021/1/22 下午 03:06
     *
     * @param users 用戶編號集合
     * @return 用戶郵箱集合
     */
    public static List getEmailsByUsers(List users){
        List> userInfos = userService.getUserByUserNo(users);
        List userEmails = new ArrayList<>();
        userInfos.forEach(u -> {
            userEmails.add((String) u.get("user_email"));
        });
        return userEmails;
    }


} 
  

方法二:使用@Resource自动注入普通变量,然后使用@PostConstruct注解将普通变量赋值给静态变量。

@PostConstruct注解说明请参见:https://blog.csdn.net/qq360694660/article/details/82877222

/**
 * @description: 自定義公共方法
 * @author: H2103424
 * @createTime: 2021/1/22 下午 02:15
 **/
@Component
public class CustomUtil {

    @Resource
    private UserService userServiceBean;
    @Resource
    private MailSendService mailSendServiceBean;

    private static UserService userService;
    private static MailSendService mailSendService;

    @PostConstruct
    public void init(){
        userService = userServiceBean;
        mailSendService = mailSendServiceBean;
    }

    /**
     * @description: 根據 用戶編號list 獲取用戶郵箱list
     * @author:  H2103424
     * @dateTime: 2021/1/22 下午 03:06
     *
     * @param users 用戶編號集合
     * @return 用戶郵箱集合
     */
    public static List getEmailsByUsers(List users){
        List> userInfos = userService.getUserByUserNo(users);
        List userEmails = new ArrayList<>();
        userInfos.forEach(u -> {
            userEmails.add((String) u.get("user_email"));
        });
        return userEmails;
    }

} 
  

 

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