@Bean 和 @Autowired注解

本文详细探讨了Spring框架中@Bean和@Autowired两个关键注解的用途。@Bean注解指示Spring容器管理某个类的实例,确保在需要时提供。而@Autowired则用于依赖注入,自动寻找并注入@Bean创建的实例,例如在本例中注入RedisTemplate,以便进行Redis数据访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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 使用了它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值