概述
有时候我们需要编写工具类,而这个工具类是普通类,需要使用到@Resource或@Autowired注解,但是普通类是无法使用这两个注解的,使用这两个注解需要进行一些处理
解决办法
给普通类加上@Component注解,然后使用@PostConstruct注解标记工具类初始化bean
示例代码
在下面这个RedisUtil类中,通过redisUtil.configProperties.
进行调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package com.ledao.util;
import com.ledao.entity.ConfigProperties; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct; import javax.annotation.Resource;
@Component public class RedisUtil {
private static RedisUtil redisUtil;
@Resource private ConfigProperties configProperties;
@PostConstruct public void init() { redisUtil = this; redisUtil.configProperties = this.configProperties; }
private static JedisPool getRedisLink() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(100); jedisPoolConfig.setMaxIdle(10); return new JedisPool(jedisPoolConfig, redisUtil.configProperties.getHost(), redisUtil.configProperties.getPort()); }
private static void closeRedis(JedisPool jedisPool, Jedis jedis) { jedis.close(); jedisPool.close(); }
private static Jedis getJedis(JedisPool jedisPool) { Jedis jedis = jedisPool.getResource(); jedis.auth(redisUtil.configProperties.getPassword()); return jedis; }
public static boolean setKey(String key, String value) { JedisPool jedisPool = getRedisLink(); Jedis jedis = getJedis(jedisPool); String result = jedis.set(key, value); closeRedis(jedisPool, jedis); return "OK".equals(result); } }
|