问题描述:
例如:想在一个静态方法中使用到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();
}
}
启动项目,进行测试
浏览器中输入地址:
控制台的打印: