Spring设值注入简单实例(spring简单应用:面向接口编程)

1.      首先新建2个接口,Person(人),Axe(斧头)接口。

Person接口

package springtest;

//定义Person接口

public interface Person {

    //Person接口里定义一个使用斧头的方法

    public void useAxe();

}

Axe接口

package springtest;

//定义Axe接口

public interface Axe {

    //Axe接口有个砍柴的方法

    public String chop();

}

2.    新建2个实现类,Chinese类,StoneAxe类。

Chinese类

package springtest;

//Chinese实现Person接口

public class Chineseimplements Person {

    //面向Axe接口编程,而不是具体的实现累

    private Axe axe;

    //默认的构造器

    public Chinese(){}

    public void setAxe(Axe axe){

        this.axe=axe;

    }

    //实现Person接口的useAxe方法

    public void useAxe() {

       System.out.println(axe.chop());

    }

}

StoneAxe类

  package springtest;

public class StoneAxeimplements Axe {

    //默认构造器

    public StoneAxe(){}

    //实现Axe接口的chop方法

    public String chop() {

       return "斧头砍柴好慢";

    }

}

3.    下面是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:p="http://www.springframework.org/schema/p"

    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="chinese" class="springtest.Chinese">

       <property name="axe">

           <ref local="stoneAxe"/>

       </property>

    </bean>

    <bean id="stoneAxe" class="springtest.StoneAxe"/>

</beans>

4.      新建一个测试类:BeanTest:

  package springtest;

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.FileSystemXmlApplicationContext;

public class BeanTest {

    public static void main(String[] args) {

       ApplicationContext ctx=new FileSystemXmlApplicationContext("D:/myEclipse/workspace2/ssh/WebRoot/WEB-INF/applicationContext.xml");

       Person p=(Person)ctx.getBean("chinese");

       p.useAxe();

    }

}

控制台打印结果:

log4j:WARN No appenders could befound for logger(org.springframework.context.support.FileSystemXmlApplicationContext).

log4j:WARN Please initialize thelog4j system properly.

斧头砍柴好慢

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值