`xml文件中的引入bean``
public class User {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
实现步骤:1.读取xml所在的位置
2.获取bean的位置 即class的位置
3.利用类的反射机制为其私有属性赋值(看蚂蚁课堂的感悟)
代码如下`
public class ClassPathXmlApplicationContext {
private String pathXml = null;
public ClassPathXmlApplicationContext(String pathXml) {
this.pathXml = pathXml;
}
public Object getBean(String beanId) throws Exception {
if (StringUtils.isEmpty(beanId)) {
throw new Exception("beanId is null");
}
SAXReader saxReader = new SAXReader();
Document read = saxReader.read(this.getClass().getClassLoader().getResource(pathXml));
// 获取到根节点
Element rootElement = read.getRootElement();
// 根节点下所有的子节点
List<Element> elements = rootElement.elements();
for (Element element : elements) {
// 获取到节点上的属性
String id = element.attributeValue("id");
if (StringUtils.isEmpty(id)) {
continue;
}
if (!id.equals(beanId)) {
continue;
}
// 使用java反射机制初始化对象
String beanClass = element.attributeValue("class");
Class<?> forName = Class.forName(beanClass);
Object newInstance = forName.newInstance();
List<Element> propertyElementList = element.elements();
for (Element el : propertyElementList) {
String name = el.attributeValue("name");
String value = el.attributeValue("value");
Field declaredField = forName.getDeclaredField(name);
//此方法必须打开才能给私有属性赋值(注意)
declaredField.setAccessible(true);
declaredField.set(newInstance, value);
}
return newInstance;
}
return null;
}
测试代码:
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext classPath = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) classPath.getBean("user1");
System.out.println(user.getUserId() + "---" + user.getUserName());
}
xml文件
<beans>
<bean id="user1" class="com.Use">
<property name="userId" value="0001"></property>
<property name="userName" value="zz"></property>
</bean>
<bean id="user2" class="com.User">
<property name="userId" value="0002"></property>
<property name="userName" value="ss"></property>
</bean>
</beans>