Spring-案例
Posted MyBatis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}
以上是关于Spring-案例的主要内容,如果未能解决你的问题,请参考以下文章
初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段
Spring boot:thymeleaf 没有正确渲染片段
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段
What's the difference between @Component, @Repository & @Service annotations in Spring?(代码片段
spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段