Spring 第一个程序

第一步:集成Spring环境:
1.采用MyEclipse开发环境来搭建Spring框架是非常方便的,操作如下:这里写图片描述
(如果自己搭建,可以引入Spring相应的jar包进来就可)

2.集成后的目录结构:
这里写图片描述

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" 
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

</beans>

第二步,编写测试用例:
定义一个接口:

public interface Person {
    public void speack();
}

定义两个实现类ChineseImpl和AmericanImpl:

public class ChineseImpl implements Person {
    private String name;
    private Integer age;
//提供name 和 age 属性的get和set方法
    @Override
    public void speack() {
        System.out.println("----ChineseImpl---> name:" + name + ",age :" + age);
    }
}
public class AmericanImpl implements Person {
    private String name;
    private Integer age;
//提供name 和 age 属性的get和set方法
    @Override
    public void speack() {
        System.out.println("----AmericanImpl ---> name:" + name + ",age :" + age);
    }
}

在application.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" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <!--每一个bean对应于一个对象,通过class指定类路径,通过id唯一区别,property属性来设置属性值  -->
    <bean id="chinese" class="com.Model.ChineseImpl">
        <property name="name" value="小明" />
        <property name="age" value="20" />
    </bean>
    <bean id="american" class="com.Model.AmericanImpl">
        <property name="name" value="Tom" />
        <property name="age" value="40" />
    </bean>
</beans>

第三步,测试

package com.Model;

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

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过getBean("id")来获取实例
        Person person1 =(Person)context.getBean("chinese");
        Person person2 =(Person)context.getBean("american");

        person1.speack();
        person2.speack();
    }
}

结果:
—-ChineseImpl—> name:小明,age :20
—-AmericanImpl—> name:Tom,age :40

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值