Eclipse中创建Spring项目的步骤

1.创建一个动态网站项目

  2.添加Spring框架的jar包

 

链接:https://pan.baidu.com/s/1AjhcveNCVokizsrrF_-YLA
提取码:gza8

 3.创建一个实体类Stutent

package com.spring;
public class Student {
    private String name;
    private String number;
    private String major;
    private String school;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public String getMajor() {
        return major;
    }
    public void setMajor(String major) {
        this.major = major;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    
}

 4.编写Spring的配置文件,该配置文件模板可以从Spring的参考手册或Spring的例子中得到,用来进行bean的配置,文件名可以自定义,一般默认为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">
   <!--配置bean信息 -->
    <bean id="student123" class="com.spring.Student">
<!--值的注入是通过setName()方法进行注入的,也叫做数据装配-->
<property name="name" value="张三"></property> <property name="number" value="123456789"></property> <property name="major" value="计算机科学与技术"></property> <property name="school" value="XXXX职业技术学院"></property> </bean> </beans>

5.创建测试类Test

package com.spring;

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

public class Test {
    public static void main(String[] args) {
//获取Ioc容器,读取配置文件,初始化spring上下文 ApplicationContext aContext
=new ClassPathXmlApplicationContext("applicationContext.xml"); //根据id获取容器中的bean Student stu= (Student) aContext.getBean("student123"); System.out.println("name="+stu.getName()); System.out.println("number="+stu.getNumber()); System.out.println("major="+stu.getMajor()); System.out.println("school="+stu.getSchool()); } }

6.运行结果

 

posted @ 2023-03-30 15:38  YorkShare  阅读(505)  评论(0编辑  收藏  举报