一、項目截圖spring
二、建立xml文件ide
三、打印機接口測試
package com.example.demo.computerTest; public interface Printer { void init(); void print(String txt); }
四、彩色打印機this
package com.example.demo.computerTest; public class ColorPrinter implements Printer { @Override public void init() { System.out.println("啓動彩色打印機!"); } @Override public void print(String txt) { System.out.println("打印彩色文字:".concat(txt)); } }
五、電腦類spa
package com.example.demo.computerTest; public class Computer { String manu; String type; Printer p; public String getManu() { return manu; } public void setManu(String manu) { this.manu = manu; } public String getType() { return type; } public void setType(String type) { this.type = type; }
//printTxt()方法接收一個參數給打印機的print()方法實現打印的功能 public void printTxt(String txt){ p.init(); p.print(txt); } public Printer getP() { return p; } public void setP(Printer p) { this.p = p; } }
六、測試類code
說明:xml
經過ClassPathXmlApplicationContext載入XML文件對象
經過向context.getBean()方法中傳入參數,獲取具體的bean,這個參數就是XML文件中的id名;blog
經過實例對象p能夠調用Computer類中的方法,能夠獲取配置文件中爲Computer類屬性設置的值。接口
package com.example.demo.computerTest; import org.springframework.context.support.ClassPathXmlApplicationContext; public class computerTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("computers.xml"); Computer p = (Computer)context.getBean("pc"); p.printTxt("Hello,spring!"); System.out.println(p.getManu()); System.out.println(p.getType()); } }
七、xml配置
說明:
經過id屬性給每一個Bean設置id;
經過class屬性設置Bean的位置
經過ref屬性能夠引用已經定義好的bean
經過property能夠操做bean中的屬性:
name屬性指定bean中的某個屬性
value爲該屬性設置指定的值
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="colorPrinter" class="com.example.demo.computerTest.ColorPrinter"/> <bean id="pc" class="com.example.demo.computerTest.Computer"> <property name="manu"> <value>蘋果</value> </property> <property name="type" value="IPad"/> <property name="p" ref="colorPrinter"/> </bean> </beans>
八、效果:
一、測試類還能夠是下面的代碼
package com.example.demo.computerTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class computerTest { public static void main(String[] args) { //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("computers.xml"); //Computer p = (Computer)context.getBean("pc"); //p.printTxt("Hello,spring!"); //System.out.println(p.getManu()); //System.out.println(p.getType()); ApplicationContext context = new ClassPathXmlApplicationContext("computers.xml"); Computer p = (Computer) context.getBean("pc"); p.printTxt("Hello,Spring!"); } }
二、效果: