目录
目录
文章目录
  1. SpringMVC与Spring的关系
  2. 什么是依赖注入?
  3. Spring配置文件

Spring MVC 学习指南

SpringMVC与Spring的关系

  • Spring框架是一个开源的企业应用开发框架,是一个轻量级的解决方案,其中包含了20多个不同的模块,其中,我们要关注的是Core模块和Bean模块,以及SpringMVC模块。SpringMVC是Spring的一个子框架。

什么是依赖注入?

  • Core模块和Bean模块提供依赖注入的解决方案。
  • 依赖注入技术作为代码可测试性的一个解决方案已经被广泛应用。
  • 很多人在使用中,并不会去区分依赖注入和控制反转(IoC)。
  • 简单来说说依赖注入是什么?

    • 假设有两个类 A,B,现在A依赖B
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class A {
    public void method_A() {
    B b = new B();
    b.method_B();
    }
    }
    • 要想使用B类中的方法,A类必须要先实例化一个B。现在B是一个具体类,通过new关键字可以直接创建B的实例。但是,如果B只是一个接口,并且有多个实现类,那么问题就会变得复杂了,如果任意选择接口B的一个实现类,那么意味着A的可重用性大大降低了,因为无法采用B的其他实现。
    • 依赖注入是这样来处理上面的情况的:接管对象的创建工作,并将该对象的引用注入到需要使用的对象中。那么,对上面的例子,依赖注入框架会分别创建对象A和对象B,将对象B注入到对象A中。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class A {
    private B b;
    public A(B b) {
    this.b = b;
    }
    public void method_A() {
    b.method_B();
    }
    }
  • 另外,在Spring2.5以后,可以通过使用@Autowired注入B接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class A {
    @Autowired
    private B b;
    public void method_A() {
    b.method_B();
    }
    }

Spring配置文件

  • 配置文件的根元素通常如下,这里的Spring的版本为4.3.5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
.....
</beans>
  • 如果需要增强Spring的配置能力,可以在schema location属性中添加相应的schema。比如SpringMVC的配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
......
</beans>