Spring bean 初始化

2018-05-31  本文已影响0人  bigfish1129
  1. 配置文件 初始化bean
    Service = SpringContextHelper.getBean(Service.class);
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
public class SpringContextHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHelper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        checkApplicationContextNotNull();
        return applicationContext;
    }

    private static void checkApplicationContextNotNull() {
        if(applicationContext == null) {
            throw new IllegalStateException("Application Context not been initialized.");
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读