spring第一节,初识IOC(二)


layout: post
author: zjhChester
header-img: img/post-bg-universe.jpg
catalog: true
tags:
- 工厂模式


Ioc /DI即用于减少程序之间的耦合性

1、JavaBean(用java编写的可重用组件)》实体类:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pJkjjz90-1580545902003)(/mdImg/工厂模式.assets/1569224481667.png)]

第一步:编写配置文件bean.properties

需要一个配置文件来配置我们的service 和 dao

注意路径必须是全限定类名(包名+类名)

Dao=dao.impl.DaoImpl
Service=service.ServiceImpl

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ac3irVWM-1580545902005)(/mdImg/工厂模式.assets/1569232538446.png)]

第二步:编写BeanFactory类

通过读取配置文件中配置(properties/xml文件)的内容,反射创建对象

package factory;

import java.io.InputStream;
import java.util.Properties;

public class BeanFactory {
    private static Properties properties;

    /**
     * 通过静态方法在类被加载的时候就加载配置文件
     * 注意事项:通过BeanFactory的类加载器加载配置文件流(找到bean.properties)
     */
    static {
        try{
//            实例化文件
            properties = new Properties();
            /*获取properties流对象    通过BeanFactory的类加载器加载配置文件流*/
            InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(is);
        }catch (Exception e){
            throw  new ExceptionInInitializerError("初始化失败BeanFactory");
        }
    }
    /**
     * 生成Bean的静态方法
     * @param beanName 从配置文件读取的键--》从而获取需要实例化的类的全限定类名
     * @return  返回实例化之后的Bean
     *
     */
   public static Object getBean(String beanName){
        Object bean = null;
        try{
            String beanPath = properties.getProperty(beanName);
            bean = Class.forName(beanPath).newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }
        return bean;
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m8YK4ARD-1580545902005)(/mdImg/工厂模式.assets/1569232499248.png)]

第三步:编写测试类

/*通过BeanFactory内部反射实例化类,实现低耦合的编程思路**/
Service service = (Service) BeanFactory.getBean("Service");

测试结果:成功实例化

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YcwaL120-1580545902005)(/mdImg/工厂模式.assets/1569234247778.png)]

发布了12 篇原创文章 · 获赞 13 · 访问量 3511
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章