一、第一个spring项目-Spring快速入门小白编

环境:idea

1.新建spring项目


截屏2019-12-30上午11.32.15.png

2.建立实体类
Student.java

package com.bb.entity;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(Integer id, String name, Integer 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 Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.建立applicationContext.xml文件
src/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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    建立Student类对应的bean 并对属性赋值-->
        <bean id="student" class="com.bb.entity.Student">
            <property name="id" value="1"></property>
            <property name="name" value="bb"></property>
            <property name="age" value="22"></property>
        </bean>
</beans>

4.建立测试类
TestSpring.java

package com.bb.service;

import com.bb.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    public static void main(String[] args) {
        //spring上下文对象:context
       ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student =(Student) context.getBean("student");
        System.out.println(student);
    }
}

输出结果:

Student{id=1, name='bb', age=22}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。