Spring_加载beans.xml简单模拟

本文通过自定义实现BeanFactory接口的ClassPathXmlApplicationContext类,详细介绍了如何使用JDOM解析XML文件来实例化并注入Bean的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用spring框架时,都会在xml中配置一些bean。这样spring就会把我们配置的组件进行管理,让我们用起来很方便,但是一直想知道它到底是怎么一回事。上网查找资料,用jdom模拟解析xml。


beans.xml

<beans>
	<bean id="u" class="com.code.dao.impl.UserDAOImpl" />
	<bean id="userService" class="com.code.service.UserService" >
		<property name="userDAO" bean="u"/>
	</bean>
	
</beans>

面向接口编程:

BeanFactory.java

package com.code.spring;

public interface BeanFactory {
	public Object getBean(String id);
}

ClassPathXmlApplicationContext.java

package com.code.spring;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class ClassPathXmlApplicationContext implements BeanFactory{


<span style="white-space:pre">	</span>HashMap<String, Object> beans = new HashMap<String, Object>();
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>public ClassPathXmlApplicationContext() throws Exception {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>SAXBuilder builder = new SAXBuilder();
<span style="white-space:pre">		</span>Document document = builder.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml"));
<span style="white-space:pre">		</span>Element root = document.getRootElement();
<span style="white-space:pre">		</span>List<Element> list = root.getChildren("bean");


<span style="white-space:pre">		</span>for (int i = 0; i < list.size(); i++) {
<span style="white-space:pre">		</span>
<span style="white-space:pre">			</span>Element element = list.get(i);
<span style="white-space:pre">			</span>String id =  element.getAttributeValue("id");
<span style="white-space:pre">			</span>String clazz = element.getAttributeValue("class");
<span style="white-space:pre">			</span>Object o = Class.forName(clazz).newInstance();
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>System.out.println("====id==========> " + id);
<span style="white-space:pre">			</span>System.out.println("====clazz=======> " + clazz);
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>beans.put(id, o);
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>for (Element propertyEl : (List<Element>)element.getChildren("property")) {
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>String name = propertyEl.getAttributeValue("name");
<span style="white-space:pre">				</span>String bean = propertyEl.getAttributeValue("bean");
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>System.out.println("====name=========> " + name);
<span style="white-space:pre">				</span>System.out.println("====bean=========> " + bean);
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>Object objBean = beans.get(bean);
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
<span style="white-space:pre">				</span>System.out.println("====method name===> " + methodName);
<span style="white-space:pre">				</span>
<span style="white-space:pre">				</span>Method m = o.getClass().getMethod(methodName, objBean.getClass().getInterfaces()[0]);
<span style="white-space:pre">				</span>m.invoke(o, objBean);
<span style="white-space:pre">				</span>
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}


<span style="white-space:pre">	</span>public Object getBean(String id) {
<span style="white-space:pre">		</span>return beans.get(id);
<span style="white-space:pre">	</span>}
}

testParse.java

import com.code.dao.UserDAO;
import com.code.model.User;
import com.code.spring.BeanFactory;
import com.code.spring.ClassPathXmlApplicationContext;


public class TestPrase {

	public static void main(String[] args) throws Exception {
		
		User user = new User();
		user.setUsername("admin");
		user.setPassword("password");
		
		BeanFactory beanFactory = new ClassPathXmlApplicationContext();

		UserDAO userDAO =  (UserDAO) beanFactory.getBean("u");
		
		userDAO.save(user);
		
		System.out.println(userDAO);
	}
}



org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderController': Injection of resource dependencies failed at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:372) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1459) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:606) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:529) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:373) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.support.DefaultListableBeanFactory.instantiateSingleton(DefaultListableBeanFactory.java:1222) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingleton(DefaultListableBeanFactory.java:1188) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:1123) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:987) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:627) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439) at org.springframework.boot.SpringApplication.run(SpringApplication.java:318) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1361) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1350) at com.sky.reids7.Reids7Application.main(Reids7Application.java:10) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderService': Injection of resource dependencies failed at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:372) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1459) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:606) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:529) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:373) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:468) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:606) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:577) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:739) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:272) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:146) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:369) ... 19 common frames omitted Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: HEXPIRE at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:804) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:546) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1375) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1205) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:569) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:529) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:373) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:468) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:606) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:577) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:739) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:272) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:146) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:369) ... 33 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: HEXPIRE at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1826) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:607) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:529) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:339) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:373) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1683) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1628) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:913) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ... 49 common frames omitted Caused by: java.lang.NoSuchFieldError: HEXPIRE at org.springframework.data.redis.connection.lettuce.LettuceConnection$TypeHints.<clinit>(LettuceConnection.java:1163) at org.springframework.data.redis.connection.lettuce.LettuceConnection.<clinit>(LettuceConnection.java:112) at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.start(LettuceConnectionFactory.java:938) at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.afterPropertiesSet(LettuceConnectionFactory.java:1009) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1873) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1822) ... 59 common frames omitted
07-17
2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Starting Servlet engine: [Apache Tomcat/9.0.33] 2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Initializing Spring embedded WebApplicationContext 2025.03.17 10:09:36|INFO |org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext|prepareWebApplicationContext()|284|Root WebApplicationContext: initialization completed in 2729 ms 2025.03.17 10:09:36|DEBUG|io.micrometer.core.util.internal.logging.InternalLoggerFactory|newDefaultFactory()|61|Using SLF4J as the default logging framework 2025.03.17 10:09:36|ERROR|org.springframework.boot.web.embedded.tomcat.TomcatStarter|onStartup()|61|Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbHealthContributor' defined in class path resource [org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributor]: Factory method 'dbHealthContributor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class 2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Stopping service [Tomcat] 2025.03.17 10:09:36|WARN |org.springframework.context.support.AbstractApplicationContext|refresh()|558|Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2025.03.17 10:09:36|INFO |org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener|logMessage()|136|
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值