Spring5 入门案例
# Spring5 入门案例
# 下载Spring5
- 使用Spring稳定版本5.2.6
- 下载地址repo.spring.io (opens new window)
第一次访问速度有点慢,耐心等待。
- 下载完毕
# 案例演示
- 打开idea,创建普通Java工程
- 导入Spring5相关jar包
- 或者使用maven引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
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
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
- 创建普通类,在这个类中创建普通方法
package com.company;
/**
* @author frx
* @version 1.0
* @date 2021/11/30 23:43
*/
public class User {
public void add(){
System.out.println("add......");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
创建spring配置文件,在配置文件配置创建的对象
- Spring配置文件使用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">
<!--配置User对象相关的创建-->
<bean id="user" class="com.company.User"></bean>
</beans>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 进行编写测试代码
package com.company.testdemo;
import com.company.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author frx
* @version 1.0
* @date 2021/11/30 23:56
*/
public class TestSpring5 {
@Test
public void testAdd(){
// 1.加载spring配置文件
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
// 2.获取配置创建的对象
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
}
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
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
上次更新: 2024/04/18, 13:08:42