梦入琼楼寒有月,行过石树冻无烟

Spring 开发环境搭建

Spinrg jar

Spring官网中主要建议开发者下载Maven和Gradle两种方式进行下载,如果不使用两者方式的开发者,可通过https://repo.spring.io/libs-release-local/org/springframework/spring/5.1.4.RELEASE/spring-framework-5.1.4.RELEASE-dist.zip直接下载Spring 5.1.4版本的Spring jar。
而在Spring jar文件解压后各个文件的说明如下:

ID DA FA
docs 用于存储包含Spring的API文档以及开发规范 /
libs 包含开发Spring应用所需要的JAR包以及源代码 /
RELEASE.jar 是Spring 开发所需要的jar 包 /libs
RELEASE-caradoc.jar Spring框架API文档压缩包 /libs
RELEASE-sources.jar 结尾的我文件是Spring框架源文件的压缩包 /libs
spring-core-5.1.4.RELEASE.jar、spring-beans-5.1.4.RELEASE.jar、spring-context-5.1.4.RELEASE-javadoc.jar 结尾的是Spring 核心容器的四个模块(Beans、Core、Context、SpEL) /libs
schema 包含Spring 应用开发所需要的schema文件,主要定义了Spring的配置文件的约束 /

Commons-logging

Spring主要依赖Apache Commons Logging组件,可通过https://downloads.apache.org//commons/logging/binaries/commons-logging-1.2-bin.zip下载,经解压后,主要使用commons-logging-1.2文件。

Spring 基本环境

导入 JRE 文件

在开发Spring应用的时候,需要引入四个基本核心类和一个Apache Commons Logging组件引入到WebContent\WEB-INF\lib\ 即可完成引入。

Spring Ioc 基本框架与流程

接口 TestDao.java

Spring是解决业务逻辑层和其让他各层的耦合问题,因此他将面向接口的编程思想贯穿于整个系统之中应用:

1
2
3
4
package Dao;
public interface TestOne {
public void sayHello();
}
接口实现类 TestDaoImpl.java
1
2
3
4
5
6
7
8
package Dao;
public class TestDaoImpl implements TestDao {
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("Hello,world!");
}
}
spring 配置文件 applicationContext.xml

一般情况下,Spring不需要开发者手敲,可通过/docs/spring-framework-reference/core.html下API说明文档中的1.2.1. Configuration Metadata处直接复制即可:

1
2
3
4
5
6
<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="test" class="dao.TestDaoImpl"/>
</beans>
测试类 Test.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import One.TestOne;

public class Test {
public static void main (String[] args) {
// 初始化Spring容器 ApplicationContext 来加载配置文件
// @SuppressWarnings 来抑制警告的关键字,有泛型未指定类型
@SuppressWarnings("resource")
ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
/*
通过容器获取到 test的
test 是配置文件中的id "<bean id="test" class="dao.TestOneImpl"/>"
*/
TestDao testdao = (TestDao)appCon.getBean("test");
testdao.sayHello();
}
}

在执行测试类后,IDE控制台中将会输出接口实现类 TestOneImpl.java内中的”public void sayHello() {“下构造变量;。而整个输出的过程中,并没有使用new运算符来创建TestOneImpl类的对象,而是通过Spring容器来实现,而这个实现的过程就是 Spring IOC的工作机制,而这个工作机制也可以理解为工厂模式。

⬅️ Go back