hoyong

导航

Java读取Properties文件


package com.itheima.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* 个创Bean象的工
*
* Bean:在算机英中,有可重用件的含
* JavaBean:用java编写的可重用件。
* javabean > 实体类
*
* 就是建我servicedao象的。
*
* 第一:需要一配置文件配置我servicedao
* 配置的容:唯一标识=全限定名(key=value)
* 第二:通过读取配置文件中配置的容,反射
*
* 我的配置文件可以是xml也可以是properties
*/
public class BeanFactory {
//Properties
private static Properties props;

//Map,用于存放我建的象。我它称容器
private static Map<String,Object> beans;

//使用静态码块为Properties赋值
static {
try {
//例化
props = new Properties();
//properties文件的流
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的Key
Enumeration keys = props.keys();
//
while (keys.hasMoreElements()){
//取出每Key
String key = keys.nextElement().toString();
//根据keyvalue
String beanPath = props.getProperty(key);
//反射
Object value = Class.forName(beanPath).newInstance();
//keyvalue存入容器中
beans.put(key,value);
}
}catch(Exception e){
throw new ExceptionInInitializerError("初始化properties");
}
}

/**
* 根据bean的名称获
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}

/**
* 根据Bean的名称获bean
* @param beanName
* @return

public static Object getBean(String beanName){
Object bean = null;
try {
String beanPath = props.getProperty(beanName);
// System.out.println(beanPath);
bean = Class.forName(beanPath).newInstance();//每次都会调用默认构造函数创
}catch (Exception e){
e.printStackTrace();
}
return bean;
}*/
}




bean.properties代码:
accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
 

posted on 2020-05-14 16:50  hoyong  阅读(342)  评论(0)    收藏  举报