Spring Boot @Autowired 注入 静态变量 或 静态方法

注:用static去定义一个注入的方法或者配置文件值变量,编译时不会有任何异常,运行时会报空指针。

Spring官方不推荐此种方法。

 原理:

https://www.cnblogs.com/chenfeng1122/p/6270217.html

解决办法

利用spring的set注入方法,通过非静态的setter方法注入静态变量 ,我们可以改成这样就静态变量可以获取到你配置的信息了。

把get,set方法的static 修饰符去掉,然后在set方法上面加@Autowired即可

/** 阿里云OSS配置查询 */
private static OSSConfMapper ossConfMapper;
/** 阿里云OSS图片上传 */
private static UploadImgOSS uploadImgOSS;

public  OSSConfMapper getOssConfMapper() {
    return ossConfMapper;
}
@Autowired
public  void setOssConfMapper(OSSConfMapper ossConfMapper) {
    UploadUtil.ossConfMapper = ossConfMapper;
}
public  UploadImgOSS getUploadImgOSS() {
    return uploadImgOSS;
}
@Autowired
public  void setUploadImgOSS(UploadImgOSS uploadImgOSS) {
    UploadUtil.uploadImgOSS = uploadImgOSS;
}

参考文档

https://blog.csdn.net/kongrun12/article/details/76246369

https://blog.csdn.net/zxl646801924/article/details/81738231

https://blog.csdn.net/u014079773/article/details/66973830

 

经过尝试,有两种实现方式

方式一:声明一个静态的变量或方法,再相应的注入一个对应的变量和方法,最后PostConstruct注解在init时实现。

代码如下

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import tylin.paas.transfers.util.DateUtil;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class ErrorHandler {


    @Value("${customer.mail.bankMail.sender}")
    private String configSender;

    private static String sender;

    @Value("${customer.mail.bankMail.receiver}")
    private String configReceiver;

    private static String receiver;

    public static ErrorHandler errorHandler;

    @Autowired
    JavaMailSender autoJavaMailSender;

    private static JavaMailSender javaMailSender;


    @PostConstruct
    public void init() {
        sender = configSender;
        receiver = configReceiver;
        javaMailSender = autoJavaMailSender;
        errorHandler = this;
    }


    public static void sendMail() {
        
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(receiver.split(";"));
        message.setSubject("your subject");
        message.setText("your content text");

        try {
            javaMailSender.send(message);
            log.info("发送邮件成功!");
        } catch (Exception e) {
            log.error("发送邮件时发生异常!", e);
        }
        
    }

}

 

方式二:(亲测可行)

在set时注入

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.tylin.TylinERPApplication;

import java.text.SimpleDateFormat;
import java.util.Date;


@Slf4j
@Component
@SpringBootTest(classes = TylinERPApplication.class)
@RunWith(SpringRunner.class)
public class MailAutoSendTest {
    private static String sender;

    //可以不要
    public  String getSender() {
        return sender;
    }
    @Value("${customer.mail.bankMail.sender}")
    public void setSender(String sender) {
        MailAutoSendTest.sender = sender;
    }

    private static String receiver;

    //可以不要
    public  String getReceiver() {
        return receiver;
    }

    @Value("${customer.mail.bankMail.receiver}")
    public void setReceiver(String receiver) {
        MailAutoSendTest.receiver = receiver;
    }


    private static JavaMailSender javaMailSender;

    public JavaMailSender getJavaMailSender(){
        return javaMailSender;
    }

    @Autowired
    public void setJavaMailSender(JavaMailSender javaMailSender){
        MailAutoSendTest.javaMailSender = javaMailSender;
    }


    @Test
    public void sendMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        log.info(sender);
        log.info(receiver);
        message.setTo(receiver.split(";"));
        message.setSubject("xxxx");

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");

        message.setText("xxxx"+dateFormat.format(date));

        try {
            javaMailSender.send(message);
            log.info("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常!", e);
        }
    }

}

亲测示例:

@Component
public class NetEleUtil {

    private static WirelessResourceProperties resProps;

    public WirelessResourceProperties getResProps() {
        return resProps;
    }

//    @Autowired
    public void setResProps(WirelessResourceProperties resProps) {
        NetEleUtil.resProps = resProps;
    }

    /**
     * 根据网元英文简称获取网元中文名称
     *
     * @param obj
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author liangzhaolin
     * @date 2020/10/22 11:00
     */
    public static String getNetEleTableCnName(String netEleType) {
        Map<String, String> tableMap = resProps.getTableCnName();
        String netEleTableCnName = tableMap.get(netEleType);

        return netEleTableCnName;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CyberOptimus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值