package com.library.util;

import java.util.Locale;

import com.library.service.AutomaticCodeService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * 项目名称:
 * 类名: SpringContextUtil
 * 描述： 获取bean的工具类，可用于在线程里面获取bean
 */
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Autowired
    private AutomaticCodeService automaticCodeService;

    /* (non Javadoc)
     * @Title: setApplicationContext
     * @Description: spring获取bean工具类
     * @param applicationContext
     * @throws BeansException
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        System.out.println("========充值系统-开始系统自检=========");
        new CheckSystem().start();
        context = applicationContext;
    }

    /**
     * 进行系统自检
     */
    class CheckSystem extends Thread {
        int i = 0;

        @Override
        public void run() {

            while (true){
                System.out.println("========自检次数:" + i + "=========");
                i++;
                automaticCodeService.automaticForTack();

                try {
                    sleep(1000 * 10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }


    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }

    public static ApplicationContext getContext() {
        return context;
    }

}