依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象

1、项目截图

依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象

2、黑白打印机类

package com.example.demo.printer;

public class GrayPrinter implements Printer{

    @Override
    public void init() {
        System.out.println("启动打印机");
    }

    @Override
    public void print(String txt) {
        System.out.println("打印黑白文字:".concat(txt));
    }
}

3、彩色打印机类

package com.example.demo.printer;

public class ColorPrinter implements Printer {
    @Override
    public void init() {
        System.out.println("启动彩色打印机!");
    }

    @Override
    public void print(String txt) {
        System.out.println("打印彩色文字:".concat(txt));
    }
}

4、电脑

package com.example.demo.printer;

/**
 * Created by Admin on 2018/5/8.
 */
public class Computer {

    Printer p;

    public void printTxt(String txt){
        p.init();
        p.print(txt);
    }

    public Printer getP() {
        return p;
    }

    public void setP(Printer p) {
        this.p = p;
    }
}

5、配置文件

依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象

printer = com.example.demo.printer.ColorPrinter

 配置文件的创建:  依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象

6、读取bean配置并创建实例类

package com.example.demo.printer;

import java.io.IOException;
import java.util.Properties;

public class GetBeans {
    private static Properties p = new Properties();
    static{
        try{
            //读取bean配置文件
            p.load(TestComputer.class.getResourceAsStream("/bean.properties"));
        }catch(IOException e){
            System.out.println("无法找到配置文件!");
        }
    }
    public static Object getBean(String keyName){
        Object o = null;
        try{
            //根据属性文件中定义的关键字创建实例
            o = Class.forName(p.get(keyName).toString()).newInstance();
        }catch (Exception e){
            System.out.println("无法实例化对象!");
        }
        return o;
    }
}

7、打印机接口

package com.example.demo.printer;
public interface Printer {
    void init();

    void print(String txt);
}

8、测试类

package com.example.demo.printer;

public class TestComputer {
    public static void main(String[] args) {
        Computer pcl = new Computer();
        //实现不用new关键字
        Printer p = (Printer) GetBeans.getBean("printer");
        pcl.setP(p);
        pcl.getP().print("打印测试页...");
    }
}

9、效果

依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象


当电脑要安装黑白打印机的时候只需要将配置文件中的printer变量的值设置为 

printer = com.example.demo.printer.GrayPrinter

这样做的好处就是实现,既不需要改变Computer类也不需要改变测试类中的代码,通过配置的方式就可以选择不同的打印机进行安装