<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean的基本配置 -->
<beanname="myBean"class="org.zhenchao.framework.MyBean"/>
</beans>
// 1. 定义资源
Resource resource = new ClassPathResource("spring-core.xml");
// 2. 利用XmlBeanFactory解析并注册bean定义
XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
// 3. 从IOC容器加载获取bean
MyBean myBean = (MyBean) beanFactory.getBean("myBean");
// 4. 使用bean
myBean.sayHello();
Resource resource = new ClassPathResource("spring-core.xml");
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
reader.loadBeanDefinitions(resource);
MyBean myBean = (MyBean) beanFactory.getBean("myBean");
myBean.sayHello();
publicXmlBeanFactory(Resource resource)throwsBeansException{
this(resource, null);
}
publicXmlBeanFactory(Resource resource, BeanFactory parentBeanFactory)throwsBeansException{
super(parentBeanFactory);
// 加载xml资源
this.reader.loadBeanDefinitions(resource);
}
publicintloadBeanDefinitions(EncodedResource encodedResource)throwsBeanDefinitionStoreException{
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
// 标记正在加载的资源,防止循环引用
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException("Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
// 获取资源的输入流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
// 构造InputSource对象
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 真正开始从XML文件中加载Bean定义
return this.doLoadBeanDefinitions(inputSource, encodedResource.getResource());
} finally {
inputStream.close();
}
} catch (IOException ex) {
throw new BeanDefinitionStoreException("IOException parsing XML document from " + encodedResource.getResource(), ex);
} finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
protectedintdoLoadBeanDefinitions(InputSource inputSource, Resource resource)throwsBeanDefinitionStoreException{
try {
// 1. 加载xml文件,获取到对应的Document(包含获取xml文件的实体解析器和验证模式)
Document doc = this.doLoadDocument(inputSource, resource);
// 2. 解析Document对象,并注册bean
return this.registerBeanDefinitions(doc, resource);
} catch (BeanDefinitionStoreException ex) {
// 这里是连环catch,省略
}
}
protectedDocumentdoLoadDocument(InputSource inputSource, Resource resource)throwsException{
return this.documentLoader.loadDocument(
inputSource,
this.getEntityResolver(), // 获取实体解析器
this.errorHandler,
this.getValidationModeForResource(resource), // 获取验证模式
this.isNamespaceAware());
}
protectedintgetValidationModeForResource(Resource resource){
int validationModeToUse = this.getValidationMode();
if (validationModeToUse != VALIDATION_AUTO) {
// 手动指定了验证模式
return validationModeToUse;
}
// 没有指定验证模式,则自动检测
int detectedMode = this.detectValidationMode(resource);
if (detectedMode != VALIDATION_AUTO) {
return detectedMode;
}
// 检测验证模式失败,默认采用XSD验证
return VALIDATION_XSD;
}
publicDocumentloadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
DocumentBuilderFactory factory = this.createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isDebugEnabled()) {
logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
}
DocumentBuilder builder = this.createDocumentBuilder(factory, entityResolver, errorHandler);
return builder.parse(inputSource);
}
publicintregisterBeanDefinitions(Document doc, Resource resource)throwsBeanDefinitionStoreException{
// 使用DefaultBeanDefinitionDocumentReader构造
BeanDefinitionDocumentReader documentReader = this.createBeanDefinitionDocumentReader();
// 记录之前已经注册的BeanDefinition个数
int countBefore = this.getRegistry().getBeanDefinitionCount();
// 加载并注册bean
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
// 返回本次加载的bean的数量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
publicvoidregisterBeanDefinitions(Document doc, XmlReaderContext readerContext){
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
// 获取文档的root结点
Element root = doc.getDocumentElement();
this.doRegisterBeanDefinitions(root);
}
protectedvoiddoRegisterBeanDefinitions(Element root){
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = this.createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
// 处理profile标签(其作用类比pom.xml中的profile)
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles =
StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
// 解析预处理,留给子类实现
this.preProcessXml(root);
// 解析并注册BeanDefinition
this.parseBeanDefinitions(root, this.delegate);
// 解析后处理,留给子类实现
this.postProcessXml(root);
this.delegate = parent;
}
protectedvoidparseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate){
if (delegate.isDefaultNamespace(root)) {
// 解析默认标签
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
// 解析默认标签
this.parseDefaultElement(ele, delegate);
} else {
// 解析自定义标签
delegate.parseCustomElement(ele);
}
}
}
} else {
// 解析自定义标签
delegate.parseCustomElement(root);
}
}
publicObjectgetBean(String name)throwsBeansException{
return this.doGetBean(name, null, null, false);
}
protected <T> TdoGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
/*
* 转化对应的beanName
*
* 传入的参数可能是alias,也可能是FactoryBean,所以需要进行解析,主要包含以下内容:
* 1. 去除FactoryBean的修饰符“&”
* 2. 取指定alias对应的最终的name
*/
final String beanName = this.transformedBeanName(name);
Object bean;
/*
* 检查缓存或者实例工厂中是否有对应的实例
*
* 为什么会一开始就进行检查?
* 因为在创建单例bean的时候会存在依赖注入的情况,而在创建依赖的时候为了避免循环依赖
* Spring创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提前曝光,即将对应的ObjectFactory加入到缓存
* 一旦下一个bean创建需要依赖上一个bean,则直接使用ObjectFactory
*/
Object sharedInstance = this.getSingleton(beanName); // 获取单例
if (sharedInstance != null && args == null) {
// 实例已经存在
if (logger.isDebugEnabled()) {
if (this.isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
} else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 返回对应的实例
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// 单例实例不存在
if (this.isPrototypeCurrentlyInCreation(beanName)) {
/*
* 只有在单例模式下才会尝试解决循环依赖问题
* 对于原型模式,如果存在循环依赖,也就是满足this.isPrototypeCurrentlyInCreation(beanName),抛出异常
*/
throw new BeanCurrentlyInCreationException(beanName);
}
BeanFactory parentBeanFactory = this.getParentBeanFactory();
if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
// 如果在beanDefinitionMap中(即所有已经加载的类中)不包含目标bean,则尝试从parentBeanFactory中检测
String nameToLookup = this.originalBeanName(name);
if (args != null) {
// 递归到BeanFactory中寻找
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
// 如果不仅仅是做类型检查,则创建bean
if (!typeCheckOnly) {
this.markBeanAsCreated(beanName);
}
try {
/*
* 将存储XML配置的GenericBeanDefinition转换成RootBeanDefinition
* 如果指定了beanName是子bean的话,同时会合并父类的相关属性
*/
final RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
this.checkMergedBeanDefinition(mbd, beanName, args);
// 获取当前bean依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
// 存在依赖,递归实例化依赖的bean
for (String dep : dependsOn) {
if (this.isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 缓存依赖调用
this.registerDependentBean(dep, beanName);
this.getBean(dep);
}
}
// 实例化依赖的bean后,实例化mbd自身
if (mbd.isSingleton()) {
// scope == singleton
sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() {
@Override
publicObjectgetObject()throwsBeansException{
try {
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
// scope == prototype
Object prototypeInstance;
try {
this.beforePrototypeCreation(beanName);
prototypeInstance = this.createBean(beanName, mbd, args);
} finally {
this.afterPrototypeCreation(beanName);
}
// 返回对应的实例
bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
// 其它scope
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
publicObjectgetObject()throwsBeansException{
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
}
});
// 返回对应的实例
bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex);
}
}
} catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// 检查需要的类型是否符合bean的实际类型,对应getBean时指定的requireType
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return this.getTypeConverter().convertIfNecessary(bean, requiredType);
} catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有