Spring核心概念和打印机案例

Spring框架由大约20个功能模块组成。这些模块被分成六个部分,Core Container、Data Access / Integration、Web、Aop、Instrumentation、Test

 

一:IOC(Inversion of Control)

即“控制反转”,不是什么技术,而是一种设计思想。在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部直接控制。

在传统的Java项目中,是通过一个类new另一个类的对象,将两个类进行关联,这样的话是程序主动去创建依赖对象,这样的话会导致类与类之间的高耦合,难于测式。

而IOC是把创建和查找依赖对象的控制权交给了容器,由容器进行注入组合对象,由这个容器来管理对象的生命周期和对象之间的关联关系,这样的话不但实现了对象之间的关联关系,所以对象与对象之间是 松散耦合,这样也方便测试,利于功能复用,更重要的是使得程序的整个体系结构变得非常灵活。

二:DI(Dependency Injection)

即“依赖注入”:IOC和DI在本质上来说是同一种东西,只不过IOC是一种设计理论,而DI则是一种实现。

组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能,而是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。

IoC的一个重点是在系统运行中,动态的向某个对象提供它所需要的其他对象。这一点是通过DI(Dependency Injection,依赖注入)来实现的

三:通过打印机案例来进一步理解IOC和DI

需要注入的属性必须要有set方法,因为Spring底层是根据属性的set方式进行注入的

目录

 

 

1.首先要引入Spring的依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

2.创建接口(Ink墨盒接口,Paper纸张接口)

package com.yjc.dao;
/**
 *墨盒
 * */
public interface Ink {
    String getColor(int r,int g,int b);
}


============================================

package com.yjc.dao;


public interface Paper {
    String newLine="\r\n";

    //输出一个字符
    void putInChar(char c);

    //获得纸张上的内容
    String  getContent();
}

3.Ink(墨盒接口)的实现类ColorInk(彩色墨盒)和GrayInk(黑白墨盒)

package com.yjc.dao;
    
import java.awt.*;
/**
 * 彩色墨盒
 * */
public class ColorInk implements Ink {
    @Override
    public String getColor(int r, int g, int b) {
        Color color=new Color(r,g,b);
        return  "#"+Integer.toHexString(color.getRGB()).substring(2);
    }
}
======================================================================
package com.yjc.dao;

/**
 * 黑白墨盒
 * */
import java.awt.*;
public class GreyInk implements Ink {
    @Override
    public String getColor(int r, int g, int b) {
        int c=(r+g+b)/3;
        Color color=new Color(c,c,c);
        return  "#"+Integer.toHexString(color.getRGB()).substring(2);
    }
}

4.Paper(纸张的实现类) TextPaper

package com.yjc.dao;

public class TextPaper implements  Paper{
    //每行的字符数
     private  int charPerLine=16;
     //每页行数
     private  int linePerPage=5;
     //纸张中的内容
     private  String content="";
     //x轴位置
     private  int posX=0;
     //y轴位置(当前行数)
     private  int posY=0;
     //当前页数
     private  int posP=1;
    @Override
    public void putInChar(char c) {
    content+=c;
    ++posX;
        //当当前行字符满了的话就换行
        if (posX==charPerLine){
            content+=Paper.newLine;
            posX=0;//换完行为第一个字符
            ++posY;

        }
        //当行数满了就换页
        if (posY==linePerPage){
            content+="====第"+posP+"页====";
            content+=Paper.newLine+Paper.newLine;
            posY=0;//换完页为第一行
            ++posP;

        }
    }

    @Override
    public String getContent() {
        String ret=this.content;
        if (!(posX==0&&posY==0)){
            int count=linePerPage-posY;
        //最后一页不满一页用空行补充完整
for (int i=0;i<count;++i){ ret+=Paper.newLine; } ret+="===第"+posP+"页==="; } return ret; } public void setCharPerLine(int charPerLine) { this.charPerLine = charPerLine; } public void setLinePerPage(int linePerPage) { this.linePerPage = linePerPage; } }

5.Printer(打印机类)

package com.yjc.dao;

public class Printer {
   //创建墨盒和纸张的接口的对象,并封装set方法
private Ink ink; private Paper paper; public void setInk(Ink ink) { this.ink = ink; } public void setPaper(Paper paper) { this.paper = paper; } public void print(String str){ System.out.println("使用"+ink.getColor(255,200,0)+"颜色打印:\n"); for (int i=0;i<str.length();++i){ paper.putInChar(str.charAt(i)); } System.out.println(paper.getContent()); } }

6.applicationContext.xml(Spring核心配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <!--id为唯一的标识,不能重名,class指向的是接口的实现类的-->
    <bean id="colorInk" class="com.yjc.dao.ColorInk"/>
    <bean id="greyInk" class="com.yjc.dao.GreyInk"/>
    <bean id="a4Paper" class="com.yjc.dao.TextPaper">
    <!--在此注入纸张的属性-->
<property name="charPerLine" value="10"/> <property name="linePerPage" value="8"/> </bean> <bean id="a5Paper" class="com.yjc.dao.TextPaper"> <property name="charPerLine" value="6"/> <property name="linePerPage" value="5"/> </bean>

  <!--组装打印机,使用彩色墨盒和a4的纸张--> <bean id="printer" class="com.yjc.dao.Printer"> <property name="ink" ref="colorInk"/> <property name="paper" ref="a4Paper"/> </bean> </beans>

7.进行测试

import com.yjc.dao.Printer;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test01 {
    @Test
    public  void test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        Printer helloSpring = (Printer) context.getBean("printer");
        String content="庆历四年春,滕子京谪守巴陵郡。越明年,政通人和,百废具兴。乃重修岳阳楼,增其旧制,刻唐贤今人诗赋于其上。属予作文以记之。" +
                "予观夫巴陵胜状,在洞庭一湖。衔远山,吞长江,浩浩汤汤,横无际涯;朝晖夕阴,气象万千。此则岳阳楼之大观也,前人之述备矣。然则北通巫峡,南极潇湘,迁客骚人,多会于此,览物之情,得无异乎?" +
                "若夫淫雨霏霏,连月不开,阴风怒号,浊浪排空;日星隐曜,山岳潜形;商旅不行,樯倾楫摧;薄暮冥冥,虎啸猿啼。登斯楼也,则有去国怀乡,忧谗畏讥,满目萧然,感极而悲者矣。" +
                "至若春和景明,波澜不惊,上下天光,一碧万顷;沙鸥翔集,锦鳞游泳;岸芷汀兰,郁郁青青。而或长烟一空,皓月千里,浮光跃金,静影沉璧,渔歌互答,此乐何极!登斯楼也,则有心旷神怡,宠辱偕忘,把酒临风,其喜洋洋者矣。" +
                "嗟夫!予尝求古仁人之心,或异二者之为,何哉?不以物喜,不以己悲;居庙堂之高则忧其民;处江湖之远则忧其君。是进亦忧,退亦忧。然则何时而乐耶?其必曰“先天下之忧而忧,后天下之乐而乐”乎。噫!微斯人,吾谁与归?" +
                "时六年九月十五日。";
        helloSpring.print(content);

    }
}

 

 

 使用的是A4的纸张在applicationContext.xml给他注入的属性是

 

 所以每一行只能有10个字符,一页只能有8行,

使用IOC和DI的好处就体现出来了,我们可以随时在配置中选择使用的纸张和墨盒,只需要注入相应的依赖,不用修改原有的代码


posted @ 2019-10-24 13:31  天戈  阅读(374)  评论(0编辑  收藏  举报