illustrate:
Compared with the previous setter injection, the constructor injection mainly modifies the computer class, adds a constructor to the computer class, and directly passes the instance to the constructor in the test class.
1. Project screenshot
2. Printer interface class
package com.example.demo.printer; public interface Printer { void init(); void print(String txt); }
3. Color printers
package com.example.demo.printer; public class ColorPrinter implements Printer { @Override public void init() { System.out.println( "Start the color printer!" ); } @Override public void print(String txt) { System.out.println( "Print color text: " .concat(txt)); } }
4. Black and white printer
package com.example.demo.printer; public class GrayPrinter implements Printer{ @Override public void init() { System.out.println( "Start the printer" ); } @Override public void print(String txt) { System.out.println( "Print black and white text: " .concat(txt)); } }
5. Read the bean configuration file and create an instance
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( "Could not find configuration file!" ); } } public static Object getBean(String keyName){ Object o = null ; try { // Create an instance according to the keyword defined in the property file o = Class.forName(p.get(keyName).toString()).newInstance(); }catch (Exception e){ System.out.println( "Unable to instantiate object!" ); } return o; } }
6. Computer
package com.example.demo.printer; public class Computer { Printer p; public Computer(Printer p) { this.p = p; } public Printer getP() { return p; } public void setP(Printer p) { this.p = p; } }
7. Test class
package com.example.demo.printer; public class TestComputer { public static void main(String[] args) { Printer p = (Printer) GetBeans.getBean("printer"); Computer pcl = new Computer(p); // The implementation does not use the new keyword pcl.getP().print("Print test page..." ); } }
8. Configuration file
printer = com.example.demo.printer.ColorPrinter
9. Effect: