后端-框架-Spring-实现动态组装的打印机
主要告诉自己ref和value的区别
ref为自己设置好的bean,直接引用
value为bean中property中的值
<?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">
<bean id="colorInk" class="cn.ink.ColorInk" />
<bean id="greyInk" class="cn.ink.GreyInk" />
<bean id="a4Paper" class="cn.ink.TextPaper">
<property name="charPerLine" value="10" />
<property name="linePerPage" value="8" />
</bean>
<bean id="b5Paper" class="cn.ink.TextPaper">
<property name="charPerLine" value="6" />
<property name="linePerPage" value="5" />
</bean>
<bean id="printer" class="cn.printer.Printer">
<property name="ink" ref="colorInk"></property>
<property name="paper" ref="b5Paper"></property>
</bean>
</beans>
以下为测试类
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.printer.Printer;
public class PrinterTest {
@Test
public void printerTest() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Printer printer = (Printer) context.getBean("printer");
String content = "几位轻量级容器的作者曾骄傲地对我说:这些容器非常有"
+ "用,因为它们实现了“控制反转”。这样的说辞让我深感迷惑:控"
+ "制反转是框架所共有的特征,如果仅仅因为使用了控制反转就认为"
+ "这些轻量级容器与众不同,就好像在说“我的轿车是与众不同的," + "因为它有4个轮子。”";
printer.print(content);
}
}