Spring快速入门

134 阅读3分钟

在我们的日常使用中,Spring总是与“SSM”、"SSH"捆绑出现,尤其是与SpringMVC紧紧联系在一起。伴随而来的是一堆繁杂的配置文件,这会导致我们对Spring没有一个清晰的认识,觉得它就是一个庞大的框架。其实不然,Spring本身是一个轻量级的框架,可以说Spring重新定义了Java。本文会简单的搭一个Spring的快速入门项目,谈谈“干净”的Spring。

搭建Spring项目

一个Spring工程,理论上只需要一个Maven依赖即可。

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>5.1.3.RELEASE</spring.version>
  </properties>    

  <dependencies>
	<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>

引入这个依赖之后,项目会添加进来Spring最核心的四个jar:

然后创建一个Bean,用于被Spring管理:

import org.springframework.stereotype.Service;

@Service
public class Student {

    private String username = "xuan";

    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

加了注解,Spring在初始化的时候就会管理这个类。我们看看能不能拿到它:

    @Test
    public void test1() {
        AnnotationConfigApplicationContext appcationContext = new 
                 AnnotationConfigApplicationContext("com.lele");
        Student student = (Student)appcationContext.getBean("student");
        System.out.println(student.getUsername());
    }

可以成功输出,但是在正常情况下我们还需要看到Spring的日志信息,以便出错的时候进行调试:

 <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>LATEST</version>
  </dependency>

再进行打印:

好了,到这里我们已经实现了Spring的项目搭建,是不是很清爽?它仅仅就是一个帮你管理对象的容器。

XSD引入

上面是采用注解的方式来管理对象,在Spring中也可以创建xml,通过配置文件的方式来管理对象。简单贴一个模板:

<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"
    default-lazy-init="false">

    <!-- 此标签的作用就是代替注解 -->
    <bean class="com.lele.Student" id="student"/>
</beans>

配置文件中除了有Spring自带的默认标签外,还会有一些扩展的自定义标签。如果要引入一个自定义的标签,需要引入其对应的XSD文件:

值得注意的是,这个xsd文件并不是从网络获取的,而是通过一个文件映射在了本地。

在这个本地的xsd文件中,我们可以看到component-scan标签:

容器加载方式

我们在获取Spring管理的对象时,Spring会把对象建好然后放在容器里。我们获取对象就需要先创建一个容器,然后再从容器里面去拿。Spring中一共有四种容器,分别对应不同的场景:

1.类路径获取配置文件

ClassPathXmlApplicationContext appcationContext = new 
    ClassPathXmlApplicationContext("spring.xml");

2.文件系统路径获取配置文件(绝对路径,基本上不用)

3.无配置文件

AnnotationConfigApplicationContext appcationContext = new 	
    AnnotationConfigApplicationContext("com.lele");

4.内嵌式加载

需要导入Spring Boot依赖使用,Spring Boot会在启动容器的同时加载内嵌的Tomcat。

 new EmbeddedWebApplicationContext();

至此,我们就了解了Spring使用的具体方法。是不是很简单呢?当然,这仅仅是Spring的开始。后面的文章会逐步剖析Spring内部的运行机制,欢迎关注哦。