被@PostConstruct修饰的方法想要使用redistemplate怎么写
时间: 2023-10-24 14:58:37 浏览: 170
被@PostConstruct修饰的方法想要使用redistemplate,可以通过在类中定义一个静态的RedisTemplate对象,并在被@PostConstruct修饰的方法中将注入的RedisTemplate对象赋值给静态对象。这样,在其他静态方法中就可以直接使用该静态对象来操作Redis了。具体代码如下所示:
```java
@Component
public class RedisUtil {
private static RedisTemplate<Object, Object> redisTemplates;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@PostConstruct
public void initialize() {
redisTemplates = this.redisTemplate;
}
// 其他静态方法可以直接使用redisTemplates来操作Redis
public static void set(Object key, Object value) {
if (key == null || value == null) {
return;
}
redisTemplates.opsForValue().set(key, value);
}
}
```
在上述代码中,被@PostConstruct修饰的initialize方法将注入的RedisTemplate对象赋值给了静态的redisTemplates对象。这样,在set方法中就可以直接使用redisTemplates来操作Redis了。
#### 引用[.reference_title]
- *1* *2* *3* [@PostConstruct注解详解](https://blog.csdn.net/weixin_52256162/article/details/128457610)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)