写一个超级入门级的spring的demo

今天初学spring框架,也见识了spring的冰山一角,先写一个spring的小demo梳理下今天的知识。

1. demo结构

最终结构

要导的jar包

2. pojo类

Student类属性:

  • stu_id(int)
  • stu_name(String)
  • cources(List<String>)

Teacher类属性:

  • t_id(int)
  • t_name(String)
  • stuMap(Map<Integer,Student>)

实现无参、有参构造函数,Getter&Setter方法。

3. spring配置文件 applictionContext.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.xsd">

    <bean id="student" class="demo.cyj.pojo.Student">
        <property name="s_id" value="1"></property>
        <property name="s_name" value="黑拐"></property>
        <property name="courses">
            <list>
                <value>语文</value>
                <value>数学</value>
                <value>英语</value>
            </list>
        </property>
    </bean>

    <bean id="teacher" class="demo.cyj.pojo.Teacher">
        <property name="t_id" value="1"></property>
        <property name="t_name" value="htc"></property>
        <property name="stuMap">
            <map>
                <entry key="1" value-ref="student"></entry>
                <entry key="2" value-ref="student"></entry>
                <entry key="3" value-ref="student"></entry>
            </map>
        </property>
    </bean>
</beans>

4. 测试类

package demo.cyj.pojo;

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

public class Test {

    public static void main(String[] args) {
        //获取配置文件信息
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //通过spring获取Student对象
        Student student = ac.getBean(Student.class);
        Student stu = ac.getBean(Student.class);
        System.out.println(student);
        System.out.println(stu);
        
        Teacher teacher = ac.getBean(Teacher.class);
        System.out.println(teacher);
    }

}

运行结果

运行结果

因为我在写的时候没有重写toString方法,所以打印的是hashCode,恰好发现一个现象,每个Student的HashCode都是一样的,那说明了spring中使用的是单例模式。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,828评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,357评论 18 399
  • 一 外面下雨了。不很急,淅淅索索。我推开玻璃门去看,空气潮湿温暖。是中午,有家长来...
    王小拙阅读 1,576评论 0 0
  • 动态就是一直在运动的过程中,没有静止下来的时候,没有停止,并且不尽一个物质成份在运动,周边一切有关,无关的都在运动...
    爱如潮水啦阅读 3,207评论 0 0
  • 四月五号是个幸运的日子东海的龙王祭奠前世的因果以甘露代酒 挥洒凡间红尘的侠客借这雨水解了乏渴 喂饱了坐骑继续挽救...
    善南阅读 1,247评论 0 2

友情链接更多精彩内容