- 配置文件 初始化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);
}
}
网友评论