IOC_自定义对象容器 创建实体类 package com . neu . entity ; import lombok . AllArgsConstructor ; import lombok . Data ; import lombok . NoArgsConstructor ; /** * @Author yqq * @Date 2022/05/12 18:23 * @Version 1.0 */ @Data @AllAr
IOC_自定义对象容器
创建实体类
package com.neu.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author yqq
* @Date 2022/05/12 18:23
* @Version 1.0
*/
public class Student {
private int id;
private String name;
private Integer age;
}
创建Dao接口和实现类
接口
public interface StudentDao {Student findById(int id);
}
实现类
public class StudentDaoImpl implements StudentDao {public Student findById(int id) {
return new Student(1,"yqq",23);
}
}
创建配置文件bean.properties
studentDao=com.neu.dao.StudentDaoImplstudentService=com.neu.service.StudentService
创建容器类
该类在类加载时读取配置文件,将配置文件中
配置的对象全部创建并放入容器中。
* @Author yqq
* @Date 2022/05/12 18:31
* @Version 1.0
* 容器类,负责管理对象,在类加载时读取配置文件并创建对象
*/
public class Container {
static Map<String,Object> map = new HashMap<>();
static {
//读取配置文件
InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");
Properties properties = new Properties();
try{
properties.load(is);
}catch (Exception e){
e.printStackTrace();
}
//遍历配置文件中的所有对象
Enumeration<Object> keys = properties.keys();
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
String value = properties.getProperty(key);
try {
//反射原理创建对象
Object o = Class.forName(value).newInstance();
map.put(key,o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//从容器中获得对象
public static Object getBean(String key){
return map.get(key);
}
}
创建Dao对象的调用者StudentService
public class StudentService {public Student findStudentById(int id){
//从容器中获取对象
StudentDao studentDao = (StudentDao)Container.getBean("studentDao");
//StudentDao studentDao = new StudentDaoImpl();
return studentDao.findById(1);
}
}
测试StudentService
public class Test {public static void main(String[] args) {
StudentService service = (StudentService)Container.getBean("studentService");
System.out.println(service.findStudentById(1));
}
}
- StudentService从容器中每次拿到的都是同一个
StudentDao对象,节约了资源。