“We use a lot of the tools that come with the Spring framework and reap the benefits of having a lot of the out of the box solutions, and not having to worry about writing a ton of additional code—so that really saves us some time and energy” ——Spring
“我们使用了很多Spring框架附带的工具,并从拥有大量开箱即用的解决方案中获益,而不必担心编写大量额外的代码,因此这确实为我们节省了一些时间和精力。”——Spring
Spring,顾名思义,春天。Spring 灵活而全面的扩展集和第三方库使开发人员能够构建几乎任何可以想象的应用程序。Spring Framework 的核心是控制反转 (IoC) 和依赖注入 (DI) 特性,为广泛的特性和功能提供了基础。
Spring的好处需要我们慢慢学习以后深入了解,话不多说,开始搭建Spring框架并运行第一个基于Spring的程序。
首先,使用Maven导入我们对Spring的依赖
<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
随便创建一个类,这里我创建的是HelloWorld,程序员标配了
public class HelloWorld {
public void sayHello(){
System.out.println("helloworld");
}
}
然后创建Spring的配置文件
命名可以随便给,这里我命名为applicationContext
在配置文件中编写一个bean,这里的id是bean 的唯一标识;class是你这个bean对应的类
到这儿,我们的基本配置就结束了,下面编写一个测试类,看一下我们的Spring怎么实现控制反转,替我们造对象
@Test
public void test(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld");
helloworld.sayHello();
}
ClassPathXmlApplicationContext:是Spring通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象
ioc.getBean()有多个方法,这里我们选用根据id获取。
以后的开发中,我们都是基于类来获取对象,因为在配置文件中的bean对于某个类来说都是唯一的,如果要获取多个对象,也可以不使用单例创建
获取到对象后,就可以调用其方法,完美!
总结:搭建Spring框架主要是写好配置文件,以后也可以使用注解,但是也不能忘了xml
一起学习,共同进步!
南风知我意,吹梦到西洲。