如何在静态方法中直接使用注入的bean对象

2018-11-22  本文已影响0人  昊家

如何在静态方法中直接使用注入的bean对象

今天遇到一个问题,就是在静态方法中无法使用@Autowired的对象,然后就搜索了一下,写下这边文章,以做记录:


问题代码

@Component

public class MobileMessageSend {

    @Autowired

    private RedisBaseOperation<String> redisBaseOperation;

public static int sendMsg(String phone) throws IOException {

        String phoneCode = JSON.parseObject(responseEntity).getString("obj");

        redisBaseOperation.putCode(phone,phoneCode);

        return 0;

}

上面的代码运行之后会报错

Error:(74, 13) java: 无法从静态上下文中引用非静态 变量 redisBaseOperation

解决方案

错误的方案

    @Autowired

    private static RedisBaseOperation<String> redisBaseOperation;

    通过注解注入的静态实例变量,取到的值为null

正确的解决方案

使用@PostConstruct注解

@PostConstruct 是从Java EE 规范开始,增加的影响Servlet声明周期的注解。被用来修饰一个非晶态的void方法,

而被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且智慧被服务器执行一次

@PostConstruct的执行顺序 在构造函数之后执行后,init()方法之前执行

修改的代码如下:

@Component

public class MobileMessageSend {

    @Autowired

    private RedisBaseOperation<String> redisBaseOperationCode;

    private static MobileMessageSend mobileMessageSend;

    public void setRedisBaseOperation(RedisBaseOperation<String> redisBaseOperation) {

        this.redisBaseOperationCode = redisBaseOperation;

    }

    public static int sendMsg(String phone) throws IOException {

        String phoneCode = JSON.parseObject(responseEntity).getString("obj");

        mobileMessageSend.redisBaseOperation.putCode(phone,phoneCode);

        return 0;

    }

}

总结:查看的了很多其他人的文档,发现大都是大同小异,写下这篇文章以备查看

上一篇下一篇

猜你喜欢

热点阅读