后端-框架-Spring-实现动态组装的打印机

29 篇文章 0 订阅
24 篇文章 0 订阅

后端-框架-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,该bean的id是colorInk,class指定该bean实例的实现类 -->
	<bean id="colorInk" class="cn.ink.ColorInk" />
	<!-- 定义灰色墨盒bean,该bean的id是greyInk,class指定该bean实例的实现类 -->
	<bean id="greyInk" class="cn.ink.GreyInk" />
	<!-- 定义A4纸张bean,该bean的id是a4Paper,class指定该bean实例的实现类 -->
	<bean id="a4Paper" class="cn.ink.TextPaper">
		<!-- property元素用来指定需要容器注入的属性,charPerLine需要容器注入, TextPaper类必须拥有setCharPerLine()方法。 注入每行字符数 -->
		<property name="charPerLine" value="10" />
		<!-- property元素用来指定需要容器注入的属性,linePerPage需要容器注入,TextPaper类必须拥有setLinePerPage()方法。 注入每页行数 -->
		<property name="linePerPage" value="8" />
	</bean>
	<!-- 定义B5纸张bean,该bean的id是b5Paper,class指定该bean实例的实现类 -->
	<bean id="b5Paper" class="cn.ink.TextPaper">
		<!-- property元素用来指定需要容器注入的属性,charPerLine需要容器注入, TextPaper类必须拥有setCharPerLine()方法。注入每行字符数 -->
		<property name="charPerLine" value="6" />
		<!-- property元素用来指定需要容器注入的属性,linePerPage需要容器注入, TextPaper类必须拥有setLinePerPage()方法。注入每页行数 -->
		<property name="linePerPage" value="5" />
	</bean>
	<!-- 组装打印机。定义打印机bean,该bean的id是printer, class指定该bean实例的实现类 -->
	<bean id="printer" class="cn.printer.Printer">
		<!-- 通过ref属性注入已经定义好的bean -->
		<!-- 注入彩色墨盒 -->
		<property name="ink" ref="colorInk"></property>
		<!-- 注入A4打印纸张 -->
		<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 bean的id来获取Printer实例
		Printer printer = (Printer) context.getBean("printer");
		String content = "几位轻量级容器的作者曾骄傲地对我说:这些容器非常有"
				+ "用,因为它们实现了“控制反转”。这样的说辞让我深感迷惑:控"
				+ "制反转是框架所共有的特征,如果仅仅因为使用了控制反转就认为"
				+ "这些轻量级容器与众不同,就好像在说“我的轿车是与众不同的," + "因为它有4个轮子。”";
		printer.print(content);
	}

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值