@Bean 和 @Autowired 做了两件完全不同的事情:
@Bean 告诉 Spring:“这是这个类的一个实例,请保留它,并在我请求时将它还给我”。
/**
* redis配置
*
* @author ruoyi
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes", "deprecation" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
@Autowired 说:“请给我一个这个类的实例,例如,一个我之前用@Bean注解创建的实例”。
@Component
public class RedisService
{
@Autowired
public RedisTemplate redisTemplate;
……
}
在本例中,@Bean 注解为 Spring 提供了 RedisTemplate,一个Redis数据访问工具类, @Autowired 使用了它。