Spring学习之旅(一)极速创建Spring框架java工程项目

编译工具:eclipse

1)创建java工程:Spring_helloworld

2)导入所需jar包:

3)创建一个实体类:

public class HelloBeans {

    private String name;
    private String course;
    private Double score;
    
    public HelloBeans(){}
    public HelloBeans(String name,String course,Double score){
        this.name=name;
        this.course=course;
        this.score=score;
    }
    
    //省略了各属性的setter/getter方法
    
}

4)创建配置文件。在/src目录下创建一个hellobean.xml。再该配置文件中配置学生具体信息。(其中beans标签中引入命名空间部分,可参考官网相关版本的示例参考)

<?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 name="stu1" class="com.edu.HelloBeans">
 <property name="name" value="张三"></property>
 <property name="course" value="数学"></property>
 <property name="score" value="95"></property>
 </bean>
 
 <bean name="stu2" class="com.edu.HelloBeans">
 <property name="name" value="李四"></property>
 <property name="course" value="物理"></property>
 <property name="score" value="88"></property>
 </bean>
 
 <bean name="stu3" class="com.edu.HelloBeans">
 <property name="name" value="王五"></property>
 <property name="course" value="计算机"></property>
 <property name="score" value="90"></property>
 </bean>
 
 </beans>

5)设计一个主方法,完成Spring容器的实例化,以及业务处理——显示3名学生的信息。

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

public class Main {

    public static void main(String[] args) {
        // 创建一个容器实例(与配置文件关联)
        ApplicationContext act = new ClassPathXmlApplicationContext("hellobean.xml");
        // 声明一个对象
        HelloBeans student;
        // 从实例容器act中,分别获取3个学生对象,并显示信息
        student = (HelloBeans) act.getBean("stu1");
        System.out.println("姓名:" + student.getName() + "课程名:" + student.getCourse() + "成绩:" + student.getScore());
        student=(HelloBeans)act.getBean("stu2");
        System.out.println("姓名:" + student.getName() + "课程名:" + student.getCourse() + "成绩:" + student.getScore());
        student=(HelloBeans)act.getBean("stu3");
        System.out.println("姓名:" + student.getName() + "课程名:" + student.getCourse() + "成绩:" + student.getScore());
        
    }

}

6)运行测试。

本篇参考书籍《Java EE框架开发技术与案例教程》

原文地址:https://www.cnblogs.com/dudududu/p/8473034.html