美文网首页
Spring bean 初始化

Spring bean 初始化

作者: bigfish1129 | 来源:发表于2018-05-31 16:35 被阅读0次
  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);
    }
}

相关文章

网友评论

      本文标题:Spring bean 初始化

      本文链接:https://www.haomeiwen.com/subject/janqsftx.html