Bean:在计算机语言中,有可重用组件的含义
-
javaBean >> 实体类
-
他就是创建我们的service和dao对象的
-
第一个:需要一个配置文件来配置我们的service和dao
-
配置的内容,唯一标识= 全限定类名(key=value)
-
第二个: 通过读取配置文件中配置的内容,反射创建对象
-
我的配置文件可以是xml 也可以是properties
BeanFactory创建第一种方式
private static Properties properties;
private static Map<String, Object> map;
static {
try {
properties = new Properties();
//InputStream in = new FileInputStream("");
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean名称获取bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
Object bean = null;
try {
String beanPath = properties.getProperty(beanName);
//解耦
bean = Class.forName(beanPath).newInstance();
//newInstance() 每次都会调用默认函数创建对象,所以不存在单例情况,而是多例,所以线程是安全的
System.out.println(bean);
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}
BeanFactory第二种方式 Map
private static Properties properties;
private static Map<String, Object> map;
static {
try {
properties = new Properties();
//InputStream in = new FileInputStream("");
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
//由于每次都重新创建对象,得到的值会变化,所以要存起来,存到容器中,MAP
map = new HashMap<String, Object>();
Enumeration keys = properties.keys();
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
Object bean = Class.forName(properties.getProperty(key)).newInstance();
map.put(key, bean);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean名称获取bean对象
* @param beanName
* @return
*/
//这样写就是单例的
public static Object getBean(String beanName){
return map.get(beanName);
}
当i 是成员变量时候
- 使用map单例,就会不安全,多人访问,会使得i一直累加
当i是局部变量时候
- 使用map单例,就不存在安全问题。
git地址:https://gitee.com/Xiaokeworksveryhard/spring_decoupling.git