Eclipse中创建Spring项目的步骤

发布时间 2023-03-30 15:41:53作者: YorkShare

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

  2.添加Spring框架的jar包

 

 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 id="student123" class="com.spring.Student">
        <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) {
        ApplicationContext aContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        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.运行结果