Spring-案例
1.导包
<!--beans-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<!--context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
2.创建类和接口
2.1 颜色
2.1.1ColorInk 类中
public class ColorInk implements Ink { public String getColor() { return "红"; } }
2.1.2 GrayInk 类中
public class GrayInk implements Ink { public String getColor() { return "白"; } }
2.1.3 Ink 接口中
public interface Ink { //获取颜色的方法 public String getColor(); }
2.2 纸张
2.2.1 A4Paper 类中
public class A4Paper implements Paper { public String getPaper() { return "A4纸"; } }
2.2.2 B5Paper 类中
public class B5Paper implements Paper { public String getPaper() { return "B5纸"; } }
2.2.3 Paper接口中
public interface Paper { public String getPaper(); }
2.3 Printer
public class Printer { private Ink ink; private Paper paper; public void print(){ System.out.println("用 "+ink.getColor()+" 颜色的墨盒在 "+paper.getPaper()+" 上打印出来 老原你敢下课吗???"); } public Ink getInk() { return ink; } public void setInk(Ink ink) { this.ink = ink; } public Paper getPaper() { return paper; } public void setPaper(Paper paper) { this.paper = paper; } }
3.applicationContext.xml文件
<?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.xsd <!--IOC--> <bean id="HappyService" class="cn.bdqn.service.HappyService"> <!--DI依赖注入--> <property name="info" value="Spring"></property> </bean> <!--打印机--> <bean id="colorInk" class="cn.bdqn.printer.ink.ColorInk"></bean> <bean id="grayInk" class="cn.bdqn.printer.ink.GrayInk"></bean> <bean id="b5Paper" class="cn.bdqn.printer.paper.B5Paper"></bean> <bean id="a4Paper" class="cn.bdqn.printer.paper.A4Paper"></bean> <bean id="pinter" class="cn.bdqn.printer.print.Printer"> <property name="ink" ref="colorInk"></property> <property name="paper" ref="a4Paper"></property> </bean> </beans>
4.测试
@Test
//打印机
public void test02(){
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Printer pp= (Printer)ctx.getBean("pinter");
pp.print();
}