初探Spring

Spring是什么,这里就不介绍了,简单的来说,Spring就是一个可以简化我们开发的框架,它的结构图如下:
这里写图片描述
它的最基础的包有Beans、Core、Context、Expression、Context-support。
Spring怎么容纳我们的程序呢?
我们写一个最简单的基于XML配置的Spring程序,由Spring管理我们的Bean。例子是人类打电话。Spring的设计原则是面向接口编程,所以我们也基于这个原则设计代码。
电话接口(Phone):

public interface Phone {
    void call();
}

人类接口(Human):

public interface Human {
    void call();
}

写两个实现:
座机实现(TelePhone):

public class TelePhone implements Phone{
    public void call() {
        System.out.println("I am calling by telephone!");
    }
}

中国人实现(ChaneseHuman):

public class ChaneseHuman implements Human{
    private Phone phone;
    public void call() {
        phone.call();
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }
}

resources下建一个文件夹spring,spring下建立一个文件pen.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">
    <bean name="phone" class="TelePhone">
    </bean>
    <bean name="human" class="ChaneseHuman">
        <property name="phone" ref="phone"/>
    </bean>
</beans>

写我们的执行类(TestMain):

public class TestMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/pen.xml");
        Human human = (Human)applicationContext.getBean("human");
        human.call();
    }
}

执行结果:

Dec 31, 2017 11:54:59 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2d6e8792: startup date [Sun Dec 31 11:54:58 CST 2017]; root of context hierarchy
Dec 31, 2017 11:54:59 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/pen.xml]
I am calling by telephone!

最简单的一个Spring管理我们的各种class的实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值