BeanFactoryPostProcessor注入spring对象

实现BeanFactoryPostProcessor重写postProcessBeanFactory()可以得到ConfigurableListableBeanFactory也就得到了spring应用的上下文环境

  //获取到spring的上下文
    private static ConfigurableListableBeanFactory beanFactory;
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }
    public static<T> T getBean(String beanName)throws  Exception{
        return (T)beanFactory.getBean(beanName);
    }
    public static<T> T getBean(Class<T> clz)throws  Exception{
        return (T) beanFactory.getBean(clz);
    }

通过Bean注入新的对象

/**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService()
    {
        return new ScheduledThreadPoolExecutor(corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())
        {
            @Override
            protected void afterExecute(Runnable r, Throwable t)
            {
                super.afterExecute(r, t);
            }
        };
    }

然后通过getBean即可获取到对象的实例