springboot整合redis时关于springboot启动加载的思考

一直纠结传统的springbmvc有web.xml配置加载spring的xml文件加载上下文和容器,springboot中添加这些配置,springboot中的@Configuration注解以前也一直用,今天看了下,原来就是加载上下文以及自定义bean到到容器,那么为什么容器不用注解@Component或者@Service注解加载到容器呢,原因@Configuration不仅是加载bean并且是启动执行,里面设置自己需要初始化的方法,在@Configuration注解的类里面的方法上配置@Bean注解下面的方法会在启动时执行,如缓存加载,自定义定时器等,并且可以用@ConditionalOnMissingBean注解给bean启动时设置读取配置参数传参,也可以用@ConfigurationProperties(prefix = "http.connection.pool")传参

 

implements ApplicationRunner 实现ApplicationRunner接口覆写run方法达到启动加载效果注意需要扫描注解如:@Component,用@Configuration注解实现启动加载bean类似xml配置bean

 

@Component
public class J2cacheRunner implements ApplicationRunner
{
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private OfficialAccountsMapper officialAccountsMapper;

    @Autowired
    private RestTemplate restTemplate;
    
    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        //启动刷新access_token
        RefreshAccessToken.refreshToken();
        // 启动加载缓存
        Map<String, CacheService> res = applicationContext.getBeansOfType(CacheService.class);
        for (CacheService value : res.values())
        {
            value.load();
        }
    }

}

 

 

implements BeanPostProcessor 实现BeanPostProcessor接口可以拿到ioc容器中所有bean做自己需要的处理如单独分装指定接口的实现类到map中

 

@Component
public class Dispatcher implements BeanPostProcessor
{
    private static Map<Company, Call> calls = new HashMap<Company, Call>();

    public static Call getCall(Company category)
    {
        return calls.get(category);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
    {
        if (bean instanceof LogisticsCall)
        {
            Call call = (Call) bean;
            calls.put(((Call) bean).category(), call);
        }
        
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
    {
        return bean;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值