Spring 第一个程序

使用 Spring 管理对象的第一个程序。

一、项目结构

二、项目文件

1. Driver 接口

1
2
3
public interface Driver {
void drive();
}

2. Car 类

1
2
3
4
5
6
public class Car implements Vehicle {
@Override
public void work() {
System.out.println("car正在工作");
}
}

3. Driver 接口

1
2
3
public interface Driver {
void drive();
}

4. DriverZhang 类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class DriverZhang implements Driver {
Vehicle vehicle;

public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}

@Override
public void drive() {
System.out.println("DriverZhang正在工作");
vehicle.work();
}
}

5. beans.xml

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="car" class="pojo.Car"/>

<bean id="driverZhang" class="pojo.DriverZhang">
<property name="vehicle" ref="car"/>
</bean>

</beans>

6. pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
···
<dependencies>
···
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
···
</dependencies>
···

三、运行测试

1
2
3
4
5
6
public void test() {
// 获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Driver driverZhang = (Driver) context.getBean("driverZhang");
driverZhang.drive();
}

参考