当我使用 @Resource 注解时候,@Value 注解的属性都无法从 application.properties 中正确读取值,值都为 null。而使用 @Autowired 的时候却可以获取正确的值。注意:当我 debug 打断点时,程序还没有走到 @Bean 注解的代码段,也就是说还没有创建 Bean。还有不管使用 @Resource 还是 @Autowired 注解都能成功的将创建的 Bean 注册到 IOC 容器中。只是使用 @Resource 注解时创建的 Bean 的属性值都为 null,也就是前面提到的 @Value 拿不到 application.properties 里的值。不知道为什么会出现这种情况?请各位指导一下。。
Bean 的依赖关系如下:jedisUtil -> jedisWritePool -> jedisPoolConfig
代码如下:
package cc.tianny.o2o.config.redis; import cc.tianny.o2o.cache.JedisPoolWriper; import cc.tianny.o2o.cache.JedisUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.JedisPoolConfig; import javax.annotation.Resource; /** * spring-redis 迁移配置 */ @Configuration public class RedisConfiguration { @Value("${redis.hostname}") private String hostname; @Value("${redis.port}") private int port; @Value("${redis.pool.maxActive}") private int maxTotal; @Value("${redis.pool.maxIdle}") private int maxIdle; @Value("${redis.pool.maxWait}") private long maxWaitMillis; @Value("${redis.pool.testOnBorrow}") private boolean testOnBorrow; // @Resource(name = "jedisPoolConfig") @Autowired private JedisPoolConfig jedisPoolConfig; // @Resource(name = "jedisWritePool") @Autowired private JedisPoolWriper jedisWritePool; // @Resource(name = "jedisUtil") @Autowired private JedisUtil jedisUtil; /** * 创建 redis 连接池的相关配置 * * @return */ @Bean(name = "jedisPoolConfig") public JedisPoolConfig createJedisPoolConfig() { JedisPoolConfig jedisPoolCOnfig= new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(maxTotal); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); jedisPoolConfig.setTestOnBorrow(testOnBorrow); return jedisPoolConfig; } @Bean(name = "jedisWritePool") public JedisPoolWriper createJedisPoolWriper() { return new JedisPoolWriper(jedisPoolConfig, hostname, port); } /** * 创建 Redis 工具类,封装好 Redis 的连接以进行相关操作 * * @return */ @Bean(name = "jedisUtil") public JedisUtil createJedisUtil() { JedisUtil jedisUtil = new JedisUtil(); jedisUtil.setJedisPool(jedisWritePool); return jedisUtil; } /** * Redis 的 key 操作 * * @return */ @Bean(name = "jedisKeys") public JedisUtil.Keys createJedisKeys() { return jedisUtil.new Keys(); } /** * Redis 的 Strings 操作 * * @return */ @Bean(name = "jedisStrings") public JedisUtil.Strings createJedisStrings() { return jedisUtil.new Strings(); } } 