Springboot bean注入 ---- Jedis注入

来源:互联网 发布:java报表框架 编辑:程序博客网 时间:2024/04/29 20:22

一、在springmvc中我们注入bean使用了xml方式,如下

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd">    <!--RedisDao-->    <bean id="redisDao" class="com.mangues.cache.RedisDao">        <constructor-arg index="0" value="${redis.ip}"/>        <constructor-arg index="1" value="${redis.port}"/>        <constructor-arg index="2" value="500"/>        <constructor-arg index="3" value="5"/>        <constructor-arg index="4" value="${redis.timeout}"/>    </bean></beans>

RedisDao代码:

public class RedisDao {    private final Logger logger = LoggerFactory.getLogger(getClass());    private final JedisPool jedisPool;    public RedisDao(String ip, int port, int maxTotal, int maxIdle, long waitMill){        JedisPoolConfig config = new JedisPoolConfig();        //控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;        //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。        config.setMaxTotal(maxTotal);        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。        config.setMaxIdle(maxIdle);        //表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;        config.setMaxWaitMillis(waitMill);        //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;        config.setTestOnBorrow(true);        jedisPool = new JedisPool(config,ip,port);    }    public <T> T getBean(String key,Class<T> targetClass){        try {            Jedis jedis = jedisPool.getResource();            try{//               byte[] bytes =  jedis.get(key.getBytes());               String bytes =  jedis.get(key);                if (bytes!=null){//                    T result = ProtoStuffSerializerUtil.deserialize(bytes, targetClass);                    T result = JSON.parseObject(bytes,targetClass);                    return result;                }            }finally {                jedis.close();            }        }catch (Exception e){            logger.error(JSON.toJSONString(e));        }        return null;    }}

使用的时候直接就可以使用了

  @Autowired  private RedisDao redisDao;

二、在springboot我们可以使用bean注解来实现bean的注入

@Configurationpublic class RedisDao{    private final Logger logger = LoggerFactory.getLogger(getClass());    private  JedisPool jedisPool;    @Value("${spring.redis.ip}")    private String ip;    @Value("${spring.redis.port}")    private int port;    @Value("${spring.redis.maxTotal}")    private int maxTotal;    @Value("${spring.redis.maxIdle}")    private int maxIdle;    @Value("${spring.redis.waitMill}")    private long waitMill;    @Bean    public RedisDao redisFactory(){        JedisPoolConfig config = new JedisPoolConfig();        //控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;        //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。        config.setMaxTotal(maxTotal);        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。        config.setMaxIdle(maxIdle);        //表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;        config.setMaxWaitMillis(waitMill);        //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;        config.setTestOnBorrow(true);        jedisPool = new JedisPool(config,ip,port);        return new RedisDao();    }    public <T> T getBean(String key,Class<T> targetClass){        try {            Jedis jedis = jedisPool.getResource();            try{//               byte[] bytes =  jedis.get(key.getBytes());               String bytes =  jedis.get(key);                if (bytes!=null){//                    T result = ProtoStuffSerializerUtil.deserialize(bytes, targetClass);                    T result = JSON.parseObject(bytes,targetClass);                    return result;                }            }finally {                jedis.close();            }        }catch (Exception e){            logger.error("Exception",e);        }        return null;    }    public <T> String putBean(String key,T object){       return putBean( key,object,60*60);    }}

代码都差不多 只要加入这连个注解就行了,spring 就会把new 的RedisDao注入到上下文中。

注意:bean注解的方法一定要是 **Factory 这种命名,不然会出错

    @Configuration    public class RedisDao{        ...    }    @Bean    public RedisDao redisFactory(){        ...        return new RedisDao();    }