1. 使用配置文件创建对象的原理
使用了反射机制
- 加载bean.xml配置文件
- 对xml文件解析操作
- 获取bean.xml文件bean标签的id和class
- 反射机制创建对象(原理代码示例)
//1. 获取类对象 Class clazz = Class.forName("com.atguigu.User"); //2. 调用方法创建对象 Object o = clazz.newInstance(); //2. 或者 Object o = clazz.getDeclaredConstructor().newInstance();
2. 代码示例
2.1 对象类的声明类
package com.atguigu;
/**
* @Author: yrf
* @description:
*/
public class User {
public void add(){
System.out.println("add...");
}
}
2.2 配置xml文件
在resources文件夹内新建xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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 id="user" class="com.atguigu.User">
</bean>
</beans>
2.3 创建对象
实际使用User对象时,通过调用xml文件来生成对象。注意需要进行类型的强转
//加载Spring的配置文件,对象创建
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = (User) context.getBean("user");//强转类型
user.add();