通过注解在静态方法中如何获取某自动注入方法中的值

问题描述:

例如:想在一个静态方法中使用到redis中的值,要如何把redis中的值取出来?

定义MyServe 接口类:

package com.example.chang.service;

public interface MyServe {

    String getName();
}

定义实现类MyServeImpl :

package com.example.chang.service.impl;

import com.example.chang.service.MyServe;
import org.springframework.stereotype.Service;

@Service
public class MyServeImpl implements MyServe {
    @Override
    public String getName() {
        return "zhangSan666";
    }
}

静态方法类RedisTest (注:这个类是关键):

package com.example.chang.controller;

import com.example.chang.service.MyServe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
@Component
public class RedisTest {

    @Autowired
    private MyServe myServe;
    public static MyServe isMyServe;

//@PostConstruct该注解被用来修饰一个非静态的void()方法。
//被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。
// PostConstruct在构造函数之后执行,init()方法之前执行。
    @PostConstruct
    public void init(){
        System.out.println("进行初始化");
        isMyServe = this.myServe;
    }

    public static String myRedis(){
        System.out.println("进入了RedisTest");
        String result = isMyServe.getName();
        System.out.println("结果:"+result);
        return result;

    }

}


测试类RedisController:

package com.example.chang.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test/redis")
public class RedisController {

    @RequestMapping("test")
    public String test(){
        System.out.println("进入controller");
        return RedisTest.myRedis();
    }
}

启动项目,进行测试

浏览器中输入地址:
在这里插入图片描述
控制台的打印:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值