Spring

因为之前重装系统忘记备份,放在c盘的代码和笔记(因为一般喜欢写到注释里),全没了。再加上一年没有敲代码,只能是从0开始敲一套完整的体系了。

安装与配置

jar去这个网址下载,找最新版

下载后解压

QQ图片20210116214711

解压后差不多是这个样子:

image-20210116214923201

一堆jar

image-20210116214946140

开发简单的Spring 必须用的5个jar

spring-aop、spring-beans、spring-context、spring-core、spring-expression

以及一个日志的jar

commons-logging

创建一个Java项目作为重新开始的第一个测试项目

这里IDE选用eclipse(简单好上手),提前装好sts插件。

image-20210116215406732

编写“第一个”SpringIOC程序

创建一个applicationContext.xml

创建一个实体Student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package top.eshyee.entity;

public class Student {
private int stuNo;
private String stuName;
private int stuAge;
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", stuAge=" + stuAge + "]";
}
}

在Spring的applicationcontext的xml中,创建一个bean

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="student" class="top.eshyee.entity.Student">
<property name="stuNo" value="1"></property>
<property name="stuAge" value="2"></property>
<property name="stuName" value="genge"></property>

</bean>
</beans>

新建一个test

尝试拿取bean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package top.eshyee.test;

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

import top.eshyee.entity.Student;

public class Test1 {
public static void main(String[] args) {
//Spring 上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

Student student=(Student) context.getBean("student");
System.out.println(student);
}
Student getStudent1() {
Student student = new Student();
student.setStuName("genge");
student.setStuNo(0);
student.setStuAge(0);
System.out.println(student);
return student;
}
}

运行结果:

Student [stuNo=1, stuName=genge, stuAge=2]