程序猿阵线联盟-汇总各类技术干货技术干货Java 杂谈

Idea下的Spring的HelloWorld项目

2018-02-26  本文已影响198人  Dalin大林

一、Spring的概述

spring模块信息

二、HelloWorld

环境:

Idea 2017.3.2

JDK 1.8.0

commons-logging-1.2.jar
spring-beans-5.0.0.RELEASE.jar
spring-context-5.0.0.RELEASE.jar
spring-core-5.0.0.RELEASE.jar
spring-expression-5.0.0.RELEASE.jar
public class Student {
    private Integer id;  // 学生的id
    private String name; // 学生的姓名
    private String age; // 学生的年龄


    public Student() {
    }

    public Student(Integer id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}
<!--配置Student类-->
<bean id="student" class="top.idalin.bean.Student">
    <!--对Student类中的属性进行配置-->
    <property name="id" value="1"></property>
    <property name="name" value="dalin"></property>
    <property name="age" value="18"></property>
</bean>
public class TestStudent {

    /**
     * 创建一个spring的IOC容器
     * 其中Application是一个接口
     * ClassPathXmlApplicationContext是ApplicationContext子接口的实现类,这是一个典型的多态的体现
     * 方法参数就是spring-config.xml配置文件
     */
    ApplicationContext ioc =
            new ClassPathXmlApplicationContext("spring-config.xml");

    @Test
    public void testStudent() {
        // 通过ioc调用getBean()方法,创建一个Student对象
        // 参数是在spring-config.xml文件中bean的id值
        Student stu = (Student) ioc.getBean("student");
        // 打印stu,注意: 这时打印的stu对象是已经给对象中属性赋值了
        System.out.println(stu);
    }
}

注意: (这里有个idea的使用小技巧)

项目的源码 SpringHelloWorld

可以移步到这里来查看原文

上一篇 下一篇

猜你喜欢

热点阅读