Spring bean 初始化

  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 getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }
}

你可能感兴趣的:(Spring bean 初始化)